focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public GetNewReservationResponse getNewReservation( GetNewReservationRequest request) throws YarnException, IOException { if (request == null) { routerMetrics.incrGetNewReservationFailedRetrieved(); String errMsg = "Missing getNewReservation request."; RouterAuditLogger.logFailu...
@Test public void testGetNewReservation() throws Exception { LOG.info("Test FederationClientInterceptor : Get NewReservation request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing getNewReservation request.", () -> interceptor.getNewReservation(null)); // normal ...
@Override public CompletableFuture<Set<String>> availableResources(NodeId nodeId, Type resourceType) { if (clusterService.getLocalNode().id().equals(nodeId)) { Set<String> resources = getLocalAvailableResources(resourceType); ...
@Test public void testAvailableResources() { MetricValue mv = new MetricValue.Builder().load(50).add(); Set<String> diskSet = ImmutableSet.of("disk1", "disk2"); diskSet.forEach(disk -> DISK_METRICS.forEach(cmt -> testUpdateMetricWithResource(cmt, mv, disk))); Set<S...
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public GenericRow apply( final GenericKey k, final GenericRow rowValue, final GenericRow aggRowValue ) { final GenericRow result = GenericRow.fromList(aggRowValue.values()); for (int idx = 0; idx < nonAggColumnCount; idx++) { ...
@Test public void shouldApplyUndoableVariadicAggregateFunctions() { when(func1.convertToInput(any())).thenAnswer( (invocation) -> { List<?> inputs = invocation.getArgument(0, List.class); return Pair.of(inputs.get(0), new VariadicArgs<>(inputs.subList(1, 4))); }...
public synchronized void post(Map<String, List<Map<String, Object>>> ruleMap) { if (ruleMap.isEmpty()) { // clear rule for (Map.Entry<String, Set<MeshRuleListener>> entry : listenerMap.entrySet()) { for (MeshRuleListener listener : entry.getValue()) { ...
@Test void post() { MeshRuleDispatcher meshRuleDispatcher = new MeshRuleDispatcher("TestApp"); Map<String, List<Map<String, Object>>> ruleMap = new HashMap<>(); List<Map<String, Object>> type1 = new LinkedList<>(); List<Map<String, Object>> type2 = new LinkedList<>(); List<M...
public static <T> Partition<T> of( int numPartitions, PartitionWithSideInputsFn<? super T> partitionFn, Requirements requirements) { Contextful ctfFn = Contextful.fn( (T element, Contextful.Fn.Context c) -> partitionFn.partitionFor(element, numPartitions, c), ...
@Test @Category(NeedsRunner.class) public void testModPartition() { PCollectionList<Integer> outputs = pipeline.apply(Create.of(1, 2, 4, 5)).apply(Partition.of(3, new ModFn())); assertTrue(outputs.size() == 3); PAssert.that(outputs.get(0)).empty(); PAssert.that(outputs.get(1)).containsInAny...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void testA0() throws Exception { String testExpression = "#a0"; String firstArgument = "test"; DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resol...
@Override public int complete(String buffer, int cursor, List<CharSequence> candidates) { if (cursor <= 0) { return cursor; } int blankPos = findLastBlank(buffer.substring(0, cursor)); String prefix = buffer.substring(blankPos + 1, cursor); String schemaName =...
@Test public void testAutoCompleteWithoutSchema() { QueryRunner runner = createQueryRunner(new ClientOptions().toClientSession()); TableNameCompleter completer = new TableNameCompleter(runner); assertEquals(completer.complete("SELECT is_infi", 14, ImmutableList.of()), 7); }
@GwtIncompatible("java.util.regex.Pattern") public void containsMatch(@Nullable Pattern regex) { checkNotNull(regex); if (actual == null) { failWithActual("expected a string that contains a match for", regex); } else if (!regex.matcher(actual).find()) { failWithActual("expected to contain a ma...
@Test public void stringContainsMatchString() { assertThat("aba").containsMatch(".*b.*"); expectFailureWhenTestingThat("aaa").containsMatch(".*b.*"); assertFailureValue("expected to contain a match for", ".*b.*"); }
public Predicate convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testEq() { ConstantOperator value = ConstantOperator.createInt(5); ScalarOperator op = new BinaryPredicateOperator(BinaryType.EQ, F0, value); Predicate result = CONVERTER.convert(op); Assert.assertTrue(result instanceof LeafPredicate); LeafPredicate leafPred...
public static VersionNumber v(String version) { return new VersionNumber(version); }
@Test void testVersionNumberConstructor() { assertThatCode(() -> v("5.0.0")).doesNotThrowAnyException(); assertThatCode(() -> v("7.0.0-alpha.1")).doesNotThrowAnyException(); assertThatCode(() -> v("23.ea.3")).doesNotThrowAnyException(); assertThatCode(() -> v("21-ea")).doesNotThrowAn...
public static TransformExecutorService parallel(ExecutorService executor) { return new ParallelTransformExecutor(executor); }
@Test public void parallelScheduleMultipleSchedulesBothImmediately() { @SuppressWarnings("unchecked") DirectTransformExecutor<Object> first = mock(DirectTransformExecutor.class); @SuppressWarnings("unchecked") DirectTransformExecutor<Object> second = mock(DirectTransformExecutor.class); Transform...
private String getUpstreamIp() { ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT); assert shenyuContext != null; if (RpcTypeEnum.HTTP.getName().equals(shenyuContext.getRpcType())) { URI uri = exchange.getAttribute(Constants.HTTP_URI); if (Objects.non...
@Test public void testGetUpstreamIp() throws Exception { loggingServerHttpResponse.setExchange(exchange); Method method1 = loggingServerHttpResponse.getClass().getDeclaredMethod("getUpstreamIp"); method1.setAccessible(true); String upstreamIp1 = (String) method1.invoke(loggingServerH...
public static String findBsn(List<Container> categorieList){ return findValue(categorieList, CATEGORIE_IDENTIFICATIENUMMERS, ELEMENT_BURGERSERVICENUMMER); }
@Test public void testEmptyElement() { Container container = new Container(); container.setNummer(CategorieUtil.CATEGORIE_IDENTIFICATIENUMMERS); Element element = new Element(); container.getElement().add(element); assertThat(CategorieUtil.findBsn(List.of(container)), nullVal...
@Override public void validateNameUniqueness(Map<CaseInsensitiveString, AbstractMaterialConfig> map) { if (StringUtils.isBlank(scmId)) { return; } if (map.containsKey(new CaseInsensitiveString(scmId))) { AbstractMaterialConfig material = map.get(new CaseInsensitiveStr...
@Test public void shouldAddErrorIfSCMNameUniquenessValidationFails() { Map<CaseInsensitiveString, AbstractMaterialConfig> nameToMaterialMap = new HashMap<>(); PluggableSCMMaterialConfig existingMaterial = new PluggableSCMMaterialConfig("scm-id"); nameToMaterialMap.put(new CaseInsensitiveStri...
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) { SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt() .orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo())); SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt() ...
@Test public void testAllowNullEncodeAndDecode() { JSONSchema<Foo> jsonSchema = JSONSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).build()); Bar bar = new Bar(); bar.setField1(true); Foo foo1 = new Foo(); foo1.setField1("foo1"); foo1.setField2("bar1")...
public Stream<T> stream() { return values.stream(); }
@Test public void shouldGetAllArgsByStream() { final VariadicArgs<Integer> varArgs = new VariadicArgs<>(ImmutableList.of(1, 2, 3)); final List<Integer> foundArgs = varArgs.stream().collect(Collectors.toList()); assertEquals(Arrays.asList(1, 2, 3), foundArgs); }
public static < T> ConsumerPath<T> matchBestPath(String requestMethod, String requestPath, List<ConsumerPath<T>> consumerPaths) { ConsumerPath<T> answer = null; List<ConsumerPath<T>> candidates = new ArrayList<>(); // first match by http method for (ConsumerPath<T> entry : ...
@Test public void testRestConsumerContextPathMatcherWithAmbiguousPaths() { List<RestConsumerContextPathMatcher.ConsumerPath<MockConsumerPath>> consumerPaths = new ArrayList<>(); consumerPaths.add(new MockConsumerPath("GET", "/camel/{a}/b/{c}")); consumerPaths.add(new MockConsumerPath("GET", ...
@Override public void modifyHandshake(final ServerEndpointConfig sec, final HandshakeRequest request, final HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); sec.getUserProperties().put(WebsocketListener.CLIENT_IP_NAME, httpSession.getAttribute(Websocket...
@Test public void testModifyHandshake() { WebsocketConfigurator websocketConfigurator = new WebsocketConfigurator(); ServerEndpointConfig sec = mock(ServerEndpointConfig.class); Map<String, Object> userProperties = mock(Map.class); when(sec.getUserProperties()).thenReturn(userPropert...
@Override public HealthStatus getStatus() { if (cr.getStatus() == ComponentStatus.INITIALIZING) return HealthStatus.INITIALIZING; PartitionHandlingManager partitionHandlingManager = cr.getComponent(PartitionHandlingManager.class); if (!isComponentHealthy() || partitionHandlingManager.getAvailabili...
@Test public void testUnhealthyStatusWithStoppingComponent() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn(ComponentStatus.STOPPING).when(componentRegistryMock).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistr...
public static Read read() { return new AutoValue_HCatalogIO_Read.Builder() .setDatabase(DEFAULT_DATABASE) .setPartitionCols(new ArrayList<>()) .build(); }
@Test public void testReadFailureTableDoesNotExist() { defaultPipeline.apply( HCatalogIO.read() .withConfigProperties(getConfigPropertiesAsMap(service.getHiveConf())) .withTable("myowntable")); thrown.expectCause(isA(NoSuchObjectException.class)); defaultPipeline.run(); }
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testNotEqMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertFalse( "Should not drop block for non-null query", canDrop(notEq(b, Binary.fromString("any")), ccmd, dictionaries)); assertTrue("Should not drop block null query", canDrop...
@Override public boolean equals(Object other) { if (this == other) return true; if(!(other instanceof HollowObjectSchema)) return false; HollowObjectSchema otherSchema = (HollowObjectSchema) other; if(!getName().equals(otherSchema.getName())) retur...
@Test public void testEquals() { { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2); s2.addField("F1", FieldTy...
public MapStateDescriptor( String name, TypeSerializer<UK> keySerializer, TypeSerializer<UV> valueSerializer) { super(name, new MapSerializer<>(keySerializer, valueSerializer), null); }
@Test void testMapStateDescriptor() throws Exception { TypeSerializer<Integer> keySerializer = new KryoSerializer<>(Integer.class, new SerializerConfigImpl()); TypeSerializer<String> valueSerializer = new KryoSerializer<>(String.class, new SerializerConfigImpl()); ...
@Override public MetricType getType() { return MetricType.GAUGE_BOOLEAN; }
@Test public void set() { BooleanGauge gauge = new BooleanGauge("bar"); assertThat(gauge.getValue()).isNull(); gauge.set(true); assertThat(gauge.getValue()).isTrue(); gauge.set(false); assertThat(gauge.getValue()).isFalse(); assertThat(gauge.getType()).isEqual...
public Materialization create( final StreamsMaterialization delegate, final MaterializationInfo info, final QueryId queryId, final QueryContext.Stacker contextStacker ) { final TransformVisitor transformVisitor = new TransformVisitor(queryId, contextStacker); final List<Transform> tran...
@Test public void shouldBuildMaterializationWithMapTransform() { // Given: factory.create(materialization, info, queryId, contextStacker); when(mapper.transform(any(), any(), any())).thenReturn(rowOut); final Transform transform = getTransform(0); // When: final Optional<GenericRow> result =...
public FEELFnResult<List<BigDecimal>> invoke(@ParameterName( "list" ) List list, @ParameterName( "match" ) Object match) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } final List<BigDecimal> result = new A...
@Test void invokeMatchNotNull() { FunctionTestUtil.assertResult(indexOfFunction.invoke(Arrays.asList("test", null, 12), "testttt"), Collections.emptyList()); FunctionTestUtil.assertResult( indexOfFunction.invoke(Arrays.asList("test", null, BigDec...
public void isEqualTo(@Nullable Object expected) { standardIsEqualTo(expected); }
@Test public void isEqualToFailureWithObjects() { Object a = OBJECT_1; Object b = OBJECT_2; expectFailure.whenTesting().that(a).isEqualTo(b); assertFailureKeys("expected", "but was"); assertFailureValue("expected", "Object 2"); assertFailureValue("but was", "Object 1"); }
public MaterializedConfiguration getConfiguration() { MaterializedConfiguration conf = new SimpleMaterializedConfiguration(); FlumeConfiguration fconfig = getFlumeConfiguration(); AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName()); if (agentConf != null) { ...
@Test public void testSourceAndSinkThrowExceptionDuringConfiguration() throws Exception { String agentName = "agent1"; String sourceType = UnconfigurableSource.class.getName(); String channelType = "memory"; String sinkType = UnconfigurableSink.class.getName(); Ma...
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/...
@Test public void AcRoleAccessControlRight() throws Exception { JwtClaims claims = ClaimsUtil.getTestClaims("stevehu", "CUSTOMER", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("account.r", "account.w"), "customer"); claims.setExpirationTimeMinutesInTheFuture(5256000); String jwt = J...
@PatchMapping("/api/v1/meetings/{uuid}/lock") public void lock(@PathVariable String uuid, @AuthAttendee long id) { meetingService.lock(uuid, id); }
@DisplayName("약속을 잠그면 200 OK를 반환한다.") @Test void lock() { Meeting meeting = meetingRepository.save(MeetingFixture.DINNER.create()); Attendee attendee = attendeeRepository.save(AttendeeFixture.HOST_JAZZ.create(meeting)); String token = getToken(attendee, meeting); RestAssured.giv...
@Override public String toString() { return "Configuration [asyncExecutorFactory=" + asyncExecutorFactory + ", balancingStrategyFactory=()->" + balancingStrategyFactory.get() + ",classLoader=" + classLoader + ", clientIntelligence=" + clientIntelligence + ", connectionPool=" + connectio...
@Test public void testHotRodURItoString() { HotRodURI uri = HotRodURI.create("hotrod://user:secret@host1?client_intelligence=BASIC"); assertEquals("hotrod://host1?client_intelligence=BASIC", uri.toString()); assertEquals("hotrod://user:secret@host1?client_intelligence=BASIC", uri.toString(true)); ...
@Override public void process() { JMeterContext context = getThreadContext(); Sampler sam = context.getCurrentSampler(); SampleResult res = context.getPreviousResult(); HTTPSamplerBase sampler; HTTPSampleResult result; if (!(sam instanceof HTTPSamplerBase) || !(res in...
@Test public void testSimpleParse3() throws Exception { HTTPSamplerBase config = makeUrlConfig(".*index.*"); config.getArguments().addArgument("param1", "value1"); HTTPSamplerBase context = makeContext("http://www.apache.org/subdir/previous.html"); String responseText = "<html><head>...
public void generate() throws IOException { packageNameByTypes.clear(); generatePackageInfo(); generateTypeStubs(); generateMessageHeaderStub(); for (final List<Token> tokens : ir.messages()) { final Token msgToken = tokens.get(0); final List<...
@Test void shouldCreateTypesInDifferentPackages() throws Exception { try (InputStream in = Tests.getLocalResource("explicit-package-test-schema.xml")) { final ParserOptions options = ParserOptions.builder().stopOnError(true).build(); final MessageSchema schema = parse(in,...
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } if (injectorSourceFromProperty == null) { if (hasInjectorSource(stepClass)) { checkOnlyOneClassHasInjectorSource(stepClass); ...
@Test void shouldThrowExceptionIfTwoDifferentInjectorSourcesAreFound() { factory = new GuiceFactory(); assertTrue(factory.addClass(YourInjectorSource.class)); Executable testMethod = () -> factory.addClass(SecondInjectorSource.class); CucumberBackendException actualThrown = assertTh...
public static Path compose(final Path root, final String path) { if(StringUtils.startsWith(path, String.valueOf(Path.DELIMITER))) { // Mount absolute path final String normalized = normalize(StringUtils.replace(path, "\\", String.valueOf(Path.DELIMITER)), true); if(StringUtil...
@Test public void testStartingWithHome() { final Path home = PathNormalizer.compose(new Path("/", EnumSet.of(Path.Type.directory)), String.format("%smyfolder/sub", Path.HOME)); assertEquals(new Path(String.format("/%smyfolder/sub", Path.HOME), EnumSet.of(Path.Type.directory)), home); assertE...
@HighFrequencyInvocation public Optional<EncryptAlgorithm> findEncryptor(final String logicColumnName) { return columns.containsKey(logicColumnName) ? Optional.of(columns.get(logicColumnName).getCipher().getEncryptor()) : Optional.empty(); }
@Test void assertFindEncryptorName() { assertTrue(encryptTable.findEncryptor("logicColumn").isPresent()); }
@Override public boolean createTopic( final String topic, final int numPartitions, final short replicationFactor, final Map<String, ?> configs, final CreateTopicsOptions createOptions ) { final Optional<Long> retentionMs = KafkaTopicClient.getRetentionMs(configs); if (isTopicE...
@Test public void shouldCreateTopicWithEmptyConfigs() { Map<String, ?> configs = ImmutableMap.of(); // When: kafkaTopicClient.createTopic("someTopic", 1, (short) 2); // Then: verify(adminClient).createTopics( eq(ImmutableSet.of(newTopic("someTopic", 1, 2, configs))), argThat(creat...
@Override public void onMsg(TbContext ctx, TbMsg msg) { JsonObject json = JsonParser.parseString(msg.getData()).getAsJsonObject(); String tmp; if (msg.getOriginator().getEntityType() != EntityType.DEVICE) { ctx.tellFailure(msg, new RuntimeException("Message originator is not a de...
@Test public void givenRetries_whenOnMsg_thenVerifyRequest() { given(ctxMock.getRpcService()).willReturn(rpcServiceMock); given(ctxMock.getTenantId()).willReturn(TENANT_ID); Integer retries = 3; TbMsgMetaData metadata = new TbMsgMetaData(); metadata.putValue(DataConstants.RE...
@Override public Schema getSourceSchema() { if (schema == null) { try { Schema.Parser parser = new Schema.Parser(); schema = parser.parse(schemaString); } catch (Exception e) { throw new HoodieSchemaException("Failed to parse schema: " + schemaString, e); } } ret...
@Test public void validateWrappedPrimitiveAndTimestampsAsRecordSchemaGeneration() throws IOException { TypedProperties properties = new TypedProperties(); properties.setProperty(ProtoClassBasedSchemaProviderConfig.PROTO_SCHEMA_CLASS_NAME.key(), Sample.class.getName()); properties.setProperty(ProtoClassBas...
@Override public Timestamp getTimestamp(final int columnIndex) throws SQLException { return (Timestamp) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Timestamp.class), Timestamp.class); }
@Test void assertGetTimestampWithColumnLabel() throws SQLException { when(mergeResultSet.getValue(1, Timestamp.class)).thenReturn(new Timestamp(0L)); assertThat(shardingSphereResultSet.getTimestamp("label"), is(new Timestamp(0L))); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { final PathAttributes attr = super.find(file, listener); if(StringUtils.isNotBlank(file.attributes().getVersionId())) { return attr.withVersionId(file.attributes().getVe...
@Test public void testFindLock() throws Exception { final Path test = new DAVTouchFeature(new NextcloudWriteFeature(session)).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); ...
public String getPrefix() { return ENABLE_HTTPS ? HTTPS_PREFIX : HTTP_PREFIX; }
@Test void testGetPrefix() { assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix()); }
@Override public OAuth2AccessTokenDO grantAuthorizationCodeForAccessToken(String clientId, String code, String redirectUri, String state) { OAuth2CodeDO codeDO = oauth2CodeService.consumeAuthorizationCode(code); Assert.notNull(codeD...
@Test public void testGrantAuthorizationCodeForAccessToken() { // 准备参数 String clientId = randomString(); String code = randomString(); List<String> scopes = Lists.newArrayList("read", "write"); String redirectUri = randomString(); String state = randomString(); ...
public static <T> T getYamlDataObject(String path, Class<T> clazz) { try (FileInputStream fis = new FileInputStream(path)) { return getYamlDataObject(fis, clazz); } catch (FileNotFoundException ignore) { return null; } catch (Exception e) { throw new AclExcept...
@SuppressWarnings("unchecked") @Test public void testGetYamlDataObject() throws IOException { try (InputStream is = AclUtilsTest.class.getClassLoader().getResourceAsStream("conf/plain_acl_correct.yml")) { Map<String, Object> map = AclUtils.getYamlDataObject(is, Map.class); Assert...
@Override public RouteContext route(final ShardingRule shardingRule) { RouteContext result = new RouteContext(); Collection<Set<String>> broadcastDataSourceGroup = getBroadcastDataSourceGroup(getDataSourceGroup(shardingRule)); for (Set<String> each : broadcastDataSourceGroup) { S...
@Test void assertRoute() { List<List<String>> shards = new LinkedList<>(); shards.add(Arrays.asList("ds1", "ds2", "ds3")); shards.add(Arrays.asList("ds1", "ds2", "ds3")); shards.add(Arrays.asList("ds1", "ds2", "ds3")); Map<String, ShardingTable> shardingTables = mockShardingT...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchOchSignalTypeTest() { Criterion criterion = Criteria.matchOchSignalType(OchSignalType.FIXED_GRID); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
public static TObjectDependencyRes listObjectDependencies(TObjectDependencyReq req) { TAuthInfo auth = req.getAuth_info(); TObjectDependencyRes response = new TObjectDependencyRes(); UserIdentity currentUser; if (auth.isSetCurrent_user_ident()) { currentUser = UserIdentity.f...
@Test public void testObjectDependencies() throws Exception { starRocksAssert.withTable("CREATE TABLE test.test_mv_base_table\n" + "(\n" + " k1 date,\n" + " k2 int,\n" + " v1 int sum\n" + ")\n" + "PARTITION BY RANGE(k1)\n" + "(...
void handleSegmentWithDeleteSegmentFinishedState(RemoteLogSegmentId remoteLogSegmentId) { // It completely removes the tracking of this segment as it is considered as deleted. unreferencedSegmentIds.remove(remoteLogSegmentId); }
@Test void handleSegmentWithDeleteSegmentFinishedState() { RemoteLogSegmentId segmentId = new RemoteLogSegmentId(tpId, Uuid.randomUuid()); epochState.handleSegmentWithCopySegmentStartedState(segmentId); assertEquals(1, epochState.unreferencedSegmentIds().size()); epochState.handleSe...
Double applyMax(double predictionDouble) { return targetField.getMax() != null ? Math.min(targetField.getMax(), predictionDouble) : predictionDouble; }
@Test void applyMax() { TargetField targetField = new TargetField(Collections.emptyList(), null, "string", null, null, null, null, null); KiePMMLTarget kiePMMLTarget = getBuilder(targetField).build(); assertThat(kiePMMLTarget.applyMax(4.33))....
public Containerizer withAdditionalTag(String tag) { Preconditions.checkArgument(ImageReference.isValidTag(tag), "invalid tag '%s'", tag); additionalTags.add(tag); return this; }
@Test public void testWithAdditionalTag() throws InvalidImageReferenceException { Containerizer containerizer = Containerizer.to(DockerDaemonImage.named("image")); containerizer.withAdditionalTag("tag"); try { containerizer.withAdditionalTag("+invalid+"); Assert.fail(); } catch (IllegalAr...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void withColon() throws ScanException { Tokenizer tokenizer = new Tokenizer("a:${b}"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "a"); Node t = witness.next = new Node(Node.Type.LITERAL, ":"); t.next = ...
public void doesNotContainCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value) { doesNotContainCell( Tables.<@Nullable Object, @Nullable Object, @Nullable Object>immutableCell( rowKey, colKey, value)); }
@Test public void doesNotContainCell() { ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val"); assertThat(table).doesNotContainCell("row", "row", "val"); assertThat(table).doesNotContainCell("col", "row", "val"); assertThat(table).doesNotContainCell("col", "col", "val"...
@Override public void setNullAt(int ordinal) { if (ordinal < metaFields.length) { metaFields[ordinal] = null; } else { sourceRow.setNullAt(rebaseOrdinal(ordinal)); } }
@Test public void testIsNullCheck() { for (int i = 0; i < 16; i++) { Object[] values = getRandomValue(true); InternalRow row = new GenericInternalRow(values); HoodieInternalRow hoodieInternalRow = new HoodieInternalRow(UTF8String.fromString("commitTime"), UTF8String.fromString("commi...
public static PMML4Result evaluate(final KiePMMLModel model, final PMMLRuntimeContext context) { if (logger.isDebugEnabled()) { logger.debug("evaluate {} {}", model, context); } addStep(() -> getStep(START, model, context.getRequestData()), context); final ProcessingDTO proce...
@Test void evaluate() { modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME); PMMLRuntimeContext pmmlContext = getPMMLContext(FILE_NAME, MODEL_NAME, memoryCompilerClassLoader); KiePMMLModelFactory kiePmmlModelFactory = PMMLLoaderUtils.loadKiePMMLModelFactory(modelLoca...
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KST...
@Test public void shouldReplaceWindowedTableSourceWithMatchingPseudoColumnVersion() { // Given: givenWindowedTable(); givenExistingQueryWithOldPseudoColumnVersion(windowedTableSource); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSou...
@Override public <K, T> UncommittedBundle<T> createKeyedBundle( StructuralKey<K> key, PCollection<T> output) { return UncommittedImmutableListBundle.create(output, key); }
@Test public void keyedWithNullKeyShouldCreateKeyedBundle() throws Exception { createKeyedBundle(VoidCoder.of(), null); }
public EndpointResponse getStatus(final String type, final String entity, final String action) { final CommandId commandId = new CommandId(type, entity, action); final Optional<CommandStatus> commandStatus = statementExecutor.getStatus(commandId); return commandStatus.map(EndpointResponse::ok) .or...
@Test public void testGetStatusNotFound() throws Exception { final StatusResource testResource = getTestStatusResource(); final EndpointResponse response = testResource.getStatus( CommandId.Type.STREAM.name(), "foo", CommandId.Action.CREATE.name()); assertThat(response.getStatus(), equalTo(NOT_FOU...
public LeaderService(WorkerService workerService, PulsarClient pulsarClient, FunctionAssignmentTailer functionAssignmentTailer, SchedulerManager schedulerManager, FunctionRuntimeManager functionRuntimeManager, ...
@Test public void testLeaderService() throws Exception { MessageId messageId = new MessageIdImpl(1, 2, -1); when(schedulerManager.getLastMessageProduced()).thenReturn(messageId); assertFalse(leaderService.isLeader()); verify(mockClient, times(1)).newConsumer(); listenerHold...
public static void assignFieldParams(Object bean, Map<String, Param> params) throws TikaConfigException { Class<?> beanClass = bean.getClass(); if (!PARAM_INFO.containsKey(beanClass)) { synchronized (TikaConfig.class) { if (!PARAM_INFO.containsKey(beanClass)) { ...
@Test public void testParserInheritance() { class Parent { @Field(required = true) int overridden; @Field(required = true) int parentField; } class Child extends Parent { @Field(required = true) int overridden; ...
@Override public Expression getExpression(String tableName, Alias tableAlias) { // 只有有登陆用户的情况下,才进行数据权限的处理 LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser == null) { return null; } // 只有管理员类型的用户,才进行数据权限的处理 if (ObjectUtil.notEqual(...
@Test // 无 LoginUser public void testGetExpression_noLoginUser() { // 准备参数 String tableName = randomString(); Alias tableAlias = new Alias(randomString()); // mock 方法 // 调用 Expression expression = rule.getExpression(tableName, tableAlias); // 断言 asser...
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowFunctionStatusStatement) { return Optional.of(new ShowFunctionStatusExecutor((ShowFu...
@Test void assertCreateWithSelectStatementForShowConnectionId() { MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class); when(selectStatement.getFrom()).thenReturn(Optional.empty()); ProjectionsSegment projectionsSegment = mock(ProjectionsSegment.class); when(projec...
List<OffsetRange> getBundleSizes(int desiredNumBundles, long start, long end) { List<OffsetRange> result = new ArrayList<>(); double[] relativeSizes = getRelativeBundleSizes(desiredNumBundles); // Generate offset ranges proportional to the relative sizes. double s = sum(relativeSizes); long startO...
@Test public void bundleSizesShouldBeProportionalToTheOneSuggestedInBundleSizeDistribution() { long expectedBundleSize = 4; options.bundleSizeDistribution = fromRealDistribution(new ConstantRealDistribution(2)); options.numRecords = 16; splitter = new BundleSplitter(options); List<OffsetRange> bu...
List<DataflowPackage> stageClasspathElements( Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) { return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions); }
@Test public void testPackageUploadIsSkippedWhenFileAlreadyExists() throws Exception { File tmpFile = makeFileWithContents("file.txt", "This is a test!"); when(mockGcsUtil.getObjects(anyListOf(GcsPath.class))) .thenReturn( ImmutableList.of( StorageObjectOrIOException.create...
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest req) { var now = clock.instant(); var bearerToken = requestBearerToken(req).orElse(null); if (bearerToken == null) { log.fine("Missing bearer token"); return Optional.of(new ErrorResponse(Response.St...
@Test void fails_for_expired_token() { var entry = new AccessLogEntry(); var req = FilterTestUtils.newRequestBuilder() .withMethod(Method.GET) .withAccessLogEntry(entry) .withHeader("Authorization", "Bearer " + READ_TOKEN.secretTokenString()) ...
public void markAsUnchanged(DefaultInputFile file) { if (isFeatureActive()) { if (file.status() != InputFile.Status.SAME) { LOG.error("File '{}' was marked as unchanged but its status is {}", file.getProjectRelativePath(), file.status()); } else { LOG.debug("File '{}' marked as unchanged...
@Test public void dont_mark_file_if_sensor_is_not_enabled() { executingSensorContext.setSensorExecuting(new SensorId("cpp", "other")); UnchangedFilesHandler handler = new UnchangedFilesHandler(enabledConfig, defaultBranchConfig, executingSensorContext); handler.markAsUnchanged(file); verifyNoInteract...
@Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK/SK 鉴权 if (StsConfig.getInstance().isStsOn()) { StsCrede...
@Test void testDoInjectWithoutResource() throws Exception { resource = new RequestResource(); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); assertEquals(3, actual.getAllKey().size()); assertEquals(Prop...
@Override public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream, ChannelPromise promise) { return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise); }
@Test public void headersWriteShouldHalfCloseAfterOnErrorForPreCreatedStream() throws Exception { final ChannelPromise promise = newPromise(); final Throwable ex = new RuntimeException(); // Fake an encoding error, like HPACK's HeaderListSizeException when(writer.writeHeaders(eq(ctx)...
public static void checkMock(Class<?> interfaceClass, AbstractInterfaceConfig config) { String mock = config.getMock(); if (ConfigUtils.isEmpty(mock)) { return; } String normalizedMock = MockInvoker.normalizeMock(mock); if (normalizedMock.startsWith(RETURN_PREFIX)) {...
@Test void checkMock1() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock("return {a, b}"); ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig); }); }
@Override public SchedulerTypeInfo getSchedulerInfo() { try { long startTime = Time.now(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); Class[] argsClasses = new Class[]{}; Object[] args = new Object[]{}; ClientMethod remoteMethod = new Clie...
@Test public void testGetSchedulerInfo() { // In this test case, we will get the return results of 4 sub-clusters. SchedulerTypeInfo typeInfo = interceptor.getSchedulerInfo(); Assert.assertNotNull(typeInfo); Assert.assertTrue(typeInfo instanceof FederationSchedulerTypeInfo); FederationSchedulerTy...
@PublicAPI(usage = ACCESS) public Set<Dependency> getDirectDependenciesToSelf() { return reverseDependencies.getDirectDependenciesTo(this); }
@Test public void direct_dependencies_to_self_by_class_type_parameters() { class ClassOtherTypeSignaturesDependOn { } @SuppressWarnings("unused") class FirstDependingOnOtherThroughTypeParameter<T extends ClassOtherTypeSignaturesDependOn> { } @SuppressWarnings("unused"...
public static EmoteClue forText(String text) { for (EmoteClue clue : CLUES) { if (clue.getText().equalsIgnoreCase(text)) { return clue; } } return null; }
@Test public void itemRequirementsFullBarrowsSetNonDegraged() { EmoteClue barrowsClue = EmoteClue.forText("Do a jig at the barrows chest. Beware of double agents! Equip any full barrows set."); ItemRequirement[] requirements = barrowsClue.getItemRequirements(); assertEquals(1, requirements.length); ItemRequ...
@Override public String buildContext() { final PluginHandleDO after = (PluginHandleDO) getAfter(); if (Objects.isNull(getBefore())) { return String.format("the plugin-handle [%s] is %s", after.getField(), StringUtils.lowerCase(getType().getType().toString())); } return St...
@Test public void deletePluginHandleBuildContextTest() { PluginHandleChangedEvent pluginChangedEvent = new PluginHandleChangedEvent(pluginHandleDO, null, EventTypeEnum.PLUGIN_HANDLE_DELETE, "test-operator"); String context = String.format("the plugin-handle [%s] is %s", pluginHandleD...
String getNodePath(BaseMetadataIdentifier metadataIdentifier) { return toRootDir() + metadataIdentifier.getUniqueKey(KeyTypeEnum.PATH); }
@Test void testConsumer() throws ClassNotFoundException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; Metada...
@Override public void execute(Object[] args) { invokeMethod(args); }
@Test void can_provide_location_of_step() throws Throwable { Method method = JavaStepDefinitionTest.class.getMethod("method_throws"); JavaStepDefinition definition = new JavaStepDefinition(method, "three (.*) mice", lookup); CucumberInvocationTargetException exception = assertThrows(Cucumber...
public static String hashKey(long value) { return encodeBase62(value, false); }
@Test public void testHashKey() { Assert.assertEquals("29C4", IdHelper.hashKey(1000000L)); Assert.assertEquals("o9oZ9l1", IdHelper.hashKey(100000000000L)); }
@Override public void setHeaders(URLConnection connection, HTTPSamplerBase sampler) throws IOException { // Get the encoding to use for the request String contentEncoding = sampler.getContentEncoding(); long contentLength = 0L; boolean hasPutBody = false; // Check if the hea...
@Test public void testSetHeadersWithNoParams() throws Exception { URLConnection uc = new NullURLConnection(); HTTPSampler sampler = new HTTPSampler(); sampler.setHTTPFiles(new HTTPFileArg[] { new HTTPFileArg("file1", "", "mime1") }); PutWriter pw = new PutWriter(); ...
public boolean hasMessagesIndexedUpTo(TimeRange timeRange) { return ProcessingNodesState.SOME_UP_TO_DATE == processingStatusService.calculateProcessingState(timeRange); }
@Test public void hasMessagesIndexedUpTo() { TimeRange any = AbsoluteRange.create("2019-01-01T00:00:00.000Z", "2019-01-01T00:00:30.000Z"); when(dbProcessingStatusService.calculateProcessingState(any)).thenReturn(ProcessingNodesState.SOME_UP_TO_DATE); assertThat(dependencyCheck.hasMessagesIn...
@Override public boolean edgeExists(String source, String target) { checkId(source); checkId(target); NodeDraftImpl sourceNode = getNode(source); NodeDraftImpl targetNode = getNode(target); if (sourceNode != null && targetNode != null) { boolean undirected = edgeD...
@Test public void testEdgeExists() { ImportContainerImpl importContainer = new ImportContainerImpl(); generateTinyGraph(importContainer); Assert.assertTrue(importContainer.edgeExists("1")); Assert.assertTrue(importContainer.edgeExists("1", "2")); Assert.assertTrue(importConta...
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldParseDropConnectorIfExistsStatement() { // Given: final String dropConnector = "DRoP CONNEcTOR IF EXISTS `jdbc-connector` ;"; // When: List<CommandParser.ParsedCommand> commands = parse(dropConnector); // Then: assertThat(commands.size(), is(1)); assertThat(comman...
public final Sensor storeLevelSensor(final String taskId, final String storeName, final String sensorSuffix, final RecordingLevel recordingLevel, final Sens...
@Test public void shouldNotUseSameStoreLevelSensorKeyWithDifferentStoreNames() { final Metrics metrics = mock(Metrics.class); final ArgumentCaptor<String> sensorKeys = setUpSensorKeyTests(metrics); final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, VERSION, ...
public static <MSG extends Message> MSG read(File file, Parser<MSG> parser) { InputStream input = null; try { input = new BufferedInputStream(new FileInputStream(file)); return parser.parseFrom(input); } catch (Exception e) { throw ContextException.of("Unable to read message", e).addContex...
@Test public void read_file_returns_empty_message_if_file_is_empty() throws Exception { File file = temp.newFile(); Fake msg = Protobuf.read(file, Fake.parser()); assertThat(msg).isNotNull(); assertThat(msg.isInitialized()).isTrue(); }
public static URLArgumentPlaceholderType valueOf(final Properties queryProps) { try { return URLArgumentPlaceholderType.valueOf(queryProps.getProperty(KEY, URLArgumentPlaceholderType.NONE.name()).toUpperCase()); } catch (final IllegalArgumentException ex) { return URLArgumentPlac...
@Test void assertValueOfWithInvalidQueryProperties() { assertThat(URLArgumentPlaceholderTypeFactory.valueOf(PropertiesBuilder.build(new Property("placeholder-type", "invalid"))), is(URLArgumentPlaceholderType.NONE)); }
@SuppressWarnings("StringSplitter") public static List<String> extractImportantUrlData(String text) throws MalformedURLException { final List<String> importantParts = new ArrayList<>(); final URL url = new URL(text); final String[] domain = url.getHost().split("\\."); //add the domai...
@Test public void testExtractImportantUrlData() throws Exception { String text = "http://github.com/jeremylong/DependencyCheck/.gitignore"; List<String> expResult = Arrays.asList("jeremylong", "DependencyCheck", "gitignore"); List<String> result = UrlStringUtils.extractImportantUrlData(text)...
@Override public ObjectNode encode(LispNatAddress address, CodecContext context) { checkNotNull(address, "LispListAddress cannot be null"); final ObjectNode result = context.mapper().createObjectNode() .put(MS_UDP_PORT_NUMBER, address.getMsUdpPortNumber()) .put(ETR_U...
@Test public void testLispNatAddressEncode() { List<MappingAddress> rtrRlocs = ImmutableList.of(MappingAddresses.ipv4MappingAddress(GLOBAL_ETR_RLOC_ADDRESS), MappingAddresses.ipv4MappingAddress(MS_RLOC_ADDRESS), MappingAddresses.ipv4MappingAdd...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testGtFloat() throws Exception { FloatColumn f = floatColumn("float_field"); float highest = Float.MIN_VALUE; for (int value : intValues) { highest = Math.max(highest, toFloat(value)); } assertTrue("Should drop: > highest value", canDrop(gt(f, highest), ccmd, dictionaries)...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchTcpDstTest() { Criterion criterion = Criteria.matchTcpDst(tpPort); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final String msg = new String(rawMessage.getPayload(), charset); try (Timer.Context ignored = this.decodeTime.time()) { final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress(); f...
@Test public void testDecodeUnstructured() throws Exception { final Message message = codec.decode(buildRawMessage(UNSTRUCTURED)); assertNotNull(message); assertEquals("c4dc57ba1ebb syslog-ng[7208]: syslog-ng starting up; version='3.5.3'", message.getMessage()); assertEquals(new Dat...
public void addFilenameChangedListener( FilenameChangedListener listener ) { if ( listener != null ) { filenameChangedListeners.add( listener ); } }
@Test public void testAddFilenameChangedListener() { meta.fireFilenameChangedListeners( "a", "a" ); meta.fireFilenameChangedListeners( "a", "b" ); meta.addFilenameChangedListener( null ); meta.fireFilenameChangedListeners( "a", "b" ); FilenameChangedListener listener = mock( FilenameChangedListene...
@Override public int count(String term) { MutableInt count = freq.get(term); return count == null ? 0 : count.value; }
@Test public void testGetBigramFrequency() { System.out.println("getBigramFrequency"); Bigram bigram = new Bigram("romantic", "comedy"); assertEquals(9, corpus.count(bigram)); }
@Override public double logp(int k) { if (k < 0) { return Double.NEGATIVE_INFINITY; } else { return lgamma(r + k) - lfactorial(k) - lgamma(r) + r * Math.log(p) + k * Math.log(1 - p); } }
@Test public void testLogP() { System.out.println("logP"); NegativeBinomialDistribution instance = new NegativeBinomialDistribution(3, 0.3); instance.rand(); assertEquals(Math.log(0.027), instance.logp(0), 1E-7); assertEquals(Math.log(0.0567), instance.logp(1), 1E-7); ...
@Override public int compare(T o1, T o2) { if (o1 == o2) return 0; if (o1 == null) return -1; if (o2 == null) return 1; return compareNonNull(o1, o2); }
@Test public void should_evaluate_non_null_instance_as_greater_than_null_instance() { // GIVEN Object o1 = "foo"; Object o2 = null; // WHEN int compare = NULL_SAFE_COMPARATOR.compare(o1, o2); // THEN then(compare).isPositive(); }
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 7) { onInvalidDataReceived(device, data); return; } // First byte: flags int offset = 0; final int flags = data.getIntValue(Data.FORMAT_UINT8,...
@Test public void onInvalidDataReceived_noTimestamp() { final DataReceivedCallback callback = new IntermediateCuffPressureDataCallback() { @Override public void onIntermediateCuffPressureReceived(@NonNull final BluetoothDevice device, final float cuffPressure, final int unit, ...
@Nonnull @SuppressWarnings("unchecked") public static <T extends Factory> T getFactoryByIdentifier( String identifier, Class<T> factoryClass) { final ServiceLoader<Factory> loader = ServiceLoader.load(Factory.class); final List<Factory> factoryList = new ArrayList<>(); for ...
@Test void getFactoryByIdentifier() { assertThat( FactoryDiscoveryUtils.getFactoryByIdentifier( "data-source-factory-1", Factory.class)) .isInstanceOf(DataSourceFactory1.class); assertThat( FactoryDiscov...
@Override public void metricChange(final KafkaMetric metric) { if (!metric.metricName().group().equals(StreamsMetricsImpl.STATE_STORE_LEVEL_GROUP)) { return; } metricRemoval(metric); final Collection<AggregatedMetric<?>> registered = registeredMetrics.get(metric.metricName().name()); ...
@Test public void shouldIgnoreMetricsFromWrongGroup() { // When: collector.metricChange(mockMetric( "some-group", RocksDBMetricsCollector.BLOCK_CACHE_USAGE, "a", BigInteger.valueOf(123) )); // Then: final Gauge<?> value = verifyAndGetRegisteredMetric(RocksD...
@Override public GetApplicationsResponse getApplications(GetApplicationsRequest request) throws YarnException, IOException { if (request == null) { routerMetrics.incrMultipleAppsFailedRetrieved(); String msg = "Missing getApplications request."; RouterAuditLogger.logFailure(user.getShortUs...
@Test public void testGetApplicationsNullRequest() throws Exception { LOG.info("Test FederationClientInterceptor: Get Applications request."); LambdaTestUtils.intercept(YarnException.class, "Missing getApplications request.", () -> interceptor.getApplications(null)); }
@Override public NacosUser authenticate(String username, String rawPassword) throws AccessException { if (StringUtils.isBlank(username) || StringUtils.isBlank(rawPassword)) { throw new AccessException("user not found!"); } NacosUserDetails nacosUserDetails = (NacosUserDetails) us...
@Test void testAuthenticate9() throws AccessException { NacosUserDetails nacosUserDetails = new NacosUserDetails(user); when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); when(jwtTokenManager.createToken(anyString())).thenReturn("token"); ...
public byte[] readAll() throws IOException { if (pos == 0 && count == buf.length) { pos = count; return buf; } byte[] ret = new byte[count - pos]; super.read(ret); return ret; }
@Test public void testConstructWithEmptyArray() throws IOException { try (ExposedByteArrayInputStream s = new ExposedByteArrayInputStream(new byte[0])) { assertEquals(0, s.available()); byte[] data = s.readAll(); assertEquals(0, data.length); } }
static Map<String, Comparable> prepareProperties(Map<String, Comparable> properties, Collection<PropertyDefinition> propertyDefinitions) { Map<String, Comparable> mappedProperties = createHashMap(propertyDefinitions.size()); for (PropertyDefinition p...
@Test public void unsatisfiedOptionalProperty() { // given Map<String, Comparable> properties = emptyMap(); Collection<PropertyDefinition> propertyDefinitions = singletonList( new SimplePropertyDefinition(PROPERTY_KEY_1, true, STRING)); // when Map<String, Co...
protected TransactionReceipt executeTransaction(Function function) throws IOException, TransactionException { return executeTransaction(function, BigInteger.ZERO); }
@Test public void testStaticEIP1559GasProvider() throws IOException, TransactionException { StaticEIP1559GasProvider gasProvider = new StaticEIP1559GasProvider(1L, BigInteger.TEN, BigInteger.ZERO, BigInteger.ONE); TransactionManager txManager = mock(TransactionManager.class); ...
public static String readLine(ByteBuffer buffer, Charset charset) { final int startPosition = buffer.position(); final int endPosition = lineEnd(buffer); if (endPosition > startPosition) { byte[] bs = readBytes(buffer, startPosition, endPosition); return StrUtil.str(bs, charset); } else if (endPosition =...
@Test public void readLineTest() { String text = "aa\r\nbbb\ncc"; ByteBuffer buffer = ByteBuffer.wrap(text.getBytes()); // 第一行 String line = BufferUtil.readLine(buffer, CharsetUtil.CHARSET_UTF_8); assertEquals("aa", line); // 第二行 line = BufferUtil.readLine(buffer, CharsetUtil.CHARSET_UTF_8); assertEq...