focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void merge(RegisterSet that) { for (int bucket = 0; bucket < M.length; bucket++) { int word = 0; for (int j = 0; j < LOG2_BITS_PER_WORD; j++) { int mask = 0x1f << (REGISTER_SIZE * j); int thisVal = (this.M[bucket] & mask); int thatV...
@Test public void testMerge() { Random rand = new Random(2); int count = 32; RegisterSet rs = new RegisterSet(count); RegisterSet[] rss = new RegisterSet[5]; for (int i = 0; i < rss.length; i++) { rss[i] = new RegisterSet(count); for (int pos = 0; po...
@PostMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId, @RequestParam("namespaceName") String namespaceName, @RequestParam(value = "namesp...
@Test void testCreateNamespaceFailure() throws NacosException { when(namespaceOperationService.createNamespace(anyString(), anyString(), anyString())).thenThrow(new NacosException(500, "test")); assertFalse(namespaceController.createNamespace("", "testName", "testDesc")); }
public static List<Object> getFieldValues(Class<? extends Enum<?>> clazz, String fieldName) { if(null == clazz || StrUtil.isBlank(fieldName)){ return null; } final Enum<?>[] enums = clazz.getEnumConstants(); if (null == enums) { return null; } final List<Object> list = new ArrayList<>(enums.length); ...
@Test public void getFieldValuesTest() { List<Object> types = EnumUtil.getFieldValues(TestEnum.class, "type"); assertEquals(CollUtil.newArrayList("type1", "type2", "type3"), types); }
@Override public RegisterRMRequestProto convert2Proto(RegisterRMRequest registerRMRequest) { final short typeCode = registerRMRequest.getTypeCode(); final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType( MessageTypeProto.forNumber(typeCode)).build...
@Test public void convert2Proto() { RegisterRMRequest registerRMRequest = new RegisterRMRequest(); registerRMRequest.setResourceIds("res1"); registerRMRequest.setVersion("123"); registerRMRequest.setTransactionServiceGroup("group"); registerRMRequest.setExtraData("extraData")...
public static boolean isIpV6Endpoint(NetworkEndpoint networkEndpoint) { return hasIpAddress(networkEndpoint) && networkEndpoint.getIpAddress().getAddressFamily().equals(AddressFamily.IPV6); }
@Test public void isIpV6Endpoint_withIpV6AndPortEndpoint_returnsFalse() { NetworkEndpoint ipV6AndPortEndpoint = NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.IP_PORT) .setPort(Port.newBuilder().setPortNumber(8888)) .setIpAddress( IpAddress.n...
@VisibleForTesting Entity exportNativeEntity(LookupTableDto lookupTableDto, EntityDescriptorIds entityDescriptorIds) { final String tableId = entityDescriptorIds.get(EntityDescriptor.create(lookupTableDto.id(), ModelTypes.LOOKUP_TABLE_V1)) .orElseThrow(() -> new ContentPackException("Couldn'...
@Test @MongoDBFixtures("LookupTableFacadeTest.json") public void exportNativeEntity() { final EntityDescriptor tableDescriptor = EntityDescriptor.create("5adf24dd4b900a0fdb4e530d", ModelTypes.LOOKUP_TABLE_V1); final EntityDescriptor adapterDescriptor = EntityDescriptor.create("5adf24a04b900a0fdb...
@Override public Buffer allocate() { return allocate(this.pageSize); }
@Test public void testWithBiggerMinimumCapacity() throws Exception { final PooledBufferAllocatorImpl allocator = new PooledBufferAllocatorImpl(4096); final Buffer buffer = allocator.allocate(10000); assertEquals(0, buffer.offset()); assertEquals(0, buffer.limit()); assertEqua...
public String reqApi(String api, Map<String, String> params, String method) throws NacosException { return reqApi(api, params, Collections.EMPTY_MAP, method); }
@Test void testReqApiForEmptyServer() throws NacosException { assertThrows(NacosException.class, () -> { Map<String, String> params = new HashMap<>(); clientProxy.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); }); }
@VisibleForTesting void startKsql(final KsqlConfig ksqlConfigWithPort) { cleanupOldState(); initialize(ksqlConfigWithPort); }
@Test public void shouldSendCreateStreamRequestBeforeSettingReady() { // When: app.startKsql(ksqlConfig); // Then: final InOrder inOrder = Mockito.inOrder(ksqlResource, serverState); verify(ksqlResource).handleKsqlStatements( securityContextArgumentCaptor.capture(), eq(new KsqlReq...
@Override public CacheAppender<O> newAppender() { return new JavaSerializationCacheAppender(); }
@Test public void fail_to_serialize() throws Exception { class Unserializable implements Serializable { private void writeObject(ObjectOutputStream out) { throw new UnsupportedOperationException("expected error"); } } DiskCache<Serializable> cache = new JavaSerializationDiskCache<>(tem...
public DynamicInputChunkContext<K, V> getChunkContext( Configuration configuration) throws IOException { if(chunkContext == null) { chunkContext = new DynamicInputChunkContext<K, V>(configuration); } return chunkContext; }
@Test public void testDynamicInputChunkContext() throws IOException { Configuration configuration = new Configuration(); configuration.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, "/tmp/test/file1.seq"); DynamicInputFormat firstInputFormat = new DynamicInputFormat(); DynamicInputFormat se...
@VisibleForTesting int getSchedulerConf(String webAppAddress, WebResource resource) throws Exception { ClientResponse response = null; resource = (resource != null) ? resource : initializeWebResource(webAppAddress); try { Builder builder; if (UserGroupInformation.isSecurityEnable...
@Test(timeout = 10000) public void testGetSchedulerConf() throws Exception { ByteArrayOutputStream sysOutStream = new ByteArrayOutputStream(); PrintStream sysOut = new PrintStream(sysOutStream); System.setOut(sysOut); try { super.setUp(); GuiceServletConfig.setInjector( Guice.cre...
@Operation(summary = "Get the status of a mijn digid session [VALID, INVALID]") @GetMapping("/session_status/{mijn_digid_session_id}") public ResponseEntity<MijnDigidSessionStatus> sessionStatus(@PathVariable(name = "mijn_digid_session_id") String mijnDigiDSessionId) { if(mijnDigiDSessionId == null) { ...
@Test void validateBadRequestOnNoSessionId() { ResponseEntity<MijnDigidSessionStatus> response = mijnDigiDSessionController.sessionStatus(null); assertEquals(response.getStatusCode(), HttpStatus.BAD_REQUEST); }
@Override public ListenableFuture<?> execute(Commit statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Session session = stateMachine.getSession(); if (!session.getTransactionId().isPres...
@Test public void testNoTransactionCommit() { TransactionManager transactionManager = createTestTransactionManager(); Session session = sessionBuilder() .build(); QueryStateMachine stateMachine = createQueryStateMachine("COMMIT", session, true, transactionManager, execut...
@Override public CompletableFuture<List<Long>> getSplitBoundary(BundleSplitOption bundleSplitOptionTmp) { FlowOrQpsEquallyDivideBundleSplitOption bundleSplitOption = (FlowOrQpsEquallyDivideBundleSplitOption) bundleSplitOptionTmp; NamespaceService service = bundleSplitOption.getServic...
@Test public void testFirstPositionIsOverLoad() { FlowOrQpsEquallyDivideBundleSplitAlgorithm algorithm = new FlowOrQpsEquallyDivideBundleSplitAlgorithm(); int loadBalancerNamespaceBundleMaxMsgRate = 1010; int loadBalancerNamespaceBundleMaxBandwidthMbytes = 100; int flowOrQpsDifferenc...
public static void mergeOutputDataParams( Map<String, Parameter> allParams, Map<String, Parameter> params) { params.forEach( (name, param) -> { if (!allParams.containsKey(name)) { throw new MaestroValidationException( "Invalid output parameter [%s], not defined in...
@Test public void testMergeOutputDataParamsMapParam() throws JsonProcessingException { Map<String, Parameter> allParams = parseParamMap( "{\"map_param\":{\"value\":{\"string_array_param\":{\"value\":[\"p1\",\"p2\"],\"type\":\"STRING_ARRAY\"},\"long_param\":{\"value\":123,\"type\":\"LONG\"},\"n...
@Override public Page<ConfigInfoTagWrapper> findAllConfigInfoTagForDumpAll(final int pageNo, final int pageSize) { final int startRow = (pageNo - 1) * pageSize; ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CON...
@Test void testFindAllConfigInfoTagForDumpAll() { //mock count Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(308); List<ConfigInfoTagWrapper> mockTagList = new ArrayList<>(); mockTagList.add(new ConfigInfoTagWrapper()); mockTagList...
public static ShutdownArgs parse(final String[] args) { try { CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(createShutdownOptions(), args); return new ShutdownArgs(StartArgsParser.getPort(cmd.getOptionValue("s"))); } catch (ParseExcept...
@Test public void should_set_shutdown_port() { assertThrows(ParseArgException.class, () -> { parse(new String[]{"shutdown", "-s"}); }); }
public void build(Entry target) { process(target, VisitorType.BUILDER); }
@Test(expected = IllegalStateException.class) public void defaultBuilderIsNotSetException() { final RecursiveMenuStructureProcessor recursiveMenuStructureBuilder = new RecursiveMenuStructureProcessor(); final Entry childEntry = new Entry(); recursiveMenuStructureBuilder.build(childEntry); }
@Override public Map<String, Map<StreamMessageId, Map<K, V>>> read(StreamMultiReadArgs args) { return get(readAsync(args)); }
@Test public void testReadMultiKeysEmpty() { RStream<String, String> stream = redisson.getStream("test2"); Map<String, Map<StreamMessageId, Map<String, String>>> s = stream.read(StreamMultiReadArgs.greaterThan(new StreamMessageId(0), "test1", new StreamMessageId(0)) ...
public ConnectionFactory connectionFactory(ConnectionFactory connectionFactory) { // It is common to implement both interfaces if (connectionFactory instanceof XAConnectionFactory) { return (ConnectionFactory) xaConnectionFactory((XAConnectionFactory) connectionFactory); } return TracingConnection...
@Test void connectionFactory_wrapsXaInput() { abstract class Both implements XAConnectionFactory, ConnectionFactory { } assertThat(jmsTracing.connectionFactory(mock(Both.class))) .isInstanceOf(XAConnectionFactory.class); }
public void go(PrintStream out) { KieServices ks = KieServices.Factory.get(); KieRepository kr = ks.getRepository(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write("src/main/resources/org/kie/example5/HAL5.drl", getRule()); KieBuilder kb = ks.newKieBuilder(kfs); ...
@Test public void testGo() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); new KieFileSystemExample().go(ps); ps.close(); String actual = baos.toString(); String expected = "" + "Dave: Hell...
public static File saveJunitXml(String targetDir, FeatureResult result, String fileName) { DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); formatter.applyPattern("0.######"); Document doc = XmlUtils.newDocument(); Element root = doc.createElement("tes...
@Test void testCustomTags() { String expectedCustomTags = "<properties><property name=\"requirement\" value=\"CALC-2\"/><property name=\"test_key\" value=\"CALC-2\"/></properties>"; Feature feature = Feature.read("classpath:com/intuit/karate/report/customTags.feature"); FeatureRuntime fr = F...
@VisibleForTesting static TableSchema protoTableSchemaFromBeamSchema(Schema schema) { Preconditions.checkState(schema.getFieldCount() > 0); TableSchema.Builder builder = TableSchema.newBuilder(); for (Field field : schema.getFields()) { builder.addFields(fieldDescriptorFromBeamField(field)); } ...
@Test public void testNestedFromSchema() { DescriptorProto descriptor = TableRowToStorageApiProto.descriptorSchemaFromTableSchema( BeamRowToStorageApiProto.protoTableSchemaFromBeamSchema((NESTED_SCHEMA)), true, false); Map<String, Type> expectedBaseTypes = BASE_SCHEMA_PROTO.getFiel...
public boolean matches(String input) { return MATCHER.matches(input, pattern); }
@Test public void testMatchesOnSingleCharacter() throws Exception { GlobMatcher matcher = new GlobMatcher("A*"); assertTrue(matcher.matches("AABBCC")); assertFalse(matcher.matches("FFFF")); }
public Optional<ContentPack> findByIdAndRevision(ModelId id, int revision) { final DBQuery.Query query = DBQuery.is(Identified.FIELD_META_ID, id).is(Revisioned.FIELD_META_REVISION, revision); return Optional.ofNullable(dbCollection.findOne(query)); }
@Test @MongoDBFixtures("ContentPackPersistenceServiceTest.json") public void findByIdAndRevisionWithInvalidId() { final Optional<ContentPack> contentPack = contentPackPersistenceService.findByIdAndRevision(ModelId.of("does-not-exist"), 2); assertThat(contentPack).isEmpty(); }
public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (actual == null) { failWithActual("expected instance of", clazz.getName()); return; } if (!isInstanceOfType(actual, clazz)) { if (Platform.classMetadataUnsupported())...
@SuppressWarnings("IsInstanceString") // test is an intentional trivially true check @Test public void isInstanceOfExactType() { assertThat("a").isInstanceOf(String.class); }
public LocationIndex prepareIndex() { return prepareIndex(EdgeFilter.ALL_EDGES); }
@Test public void testMoreReal() { BaseGraph graph = new BaseGraph.Builder(encodingManager).create(); NodeAccess na = graph.getNodeAccess(); na.setNode(1, 51.2492152, 9.4317166); na.setNode(0, 52, 9); na.setNode(2, 51.2, 9.4); na.setNode(3, 49, 10); graph.edg...
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by( PredicateT predicate) { return new Filter<>(predicate); }
@Test @Category(NeedsRunner.class) public void testIdentityFilterByPredicateWithLambda() { PCollection<Integer> output = p.apply(Create.of(591, 11789, 1257, 24578, 24799, 307)).apply(Filter.by(i -> true)); PAssert.that(output).containsInAnyOrder(591, 11789, 1257, 24578, 24799, 307); p.run(); ...
private static Schema optional(Schema original) { // null is first in the union because Parquet's default is always null return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), original)); }
@Test public void testOldAvroListOfLists() throws Exception { Schema listOfLists = optional(Schema.createArray(Schema.createArray(Schema.create(INT)))); Schema schema = Schema.createRecord("AvroCompatListInList", null, null, false); schema.setFields( Lists.newArrayList(new Schema.Field("listOfList...
@Override public void start() { DatabaseVersion.Status status = version.getStatus(); checkState(status == UP_TO_DATE || status == FRESH_INSTALL, "Compute Engine can't start unless Database is up to date"); }
@Test public void start_has_no_effect_if_status_is_FRESH_INSTALL() { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.FRESH_INSTALL); underTest.start(); verify(databaseVersion).getStatus(); verifyNoMoreInteractions(databaseVersion); }
@Override public ClientDetailsEntity updateClient(ClientDetailsEntity oldClient, ClientDetailsEntity newClient) throws IllegalArgumentException { if (oldClient != null && newClient != null) { for (String uri : newClient.getRegisteredRedirectUri()) { if (blacklistedSiteService.isBlacklisted(uri)) { throw...
@Test public void updateClient_noOfflineAccess() { ClientDetailsEntity oldClient = new ClientDetailsEntity(); oldClient.getScope().add(SystemScopeService.OFFLINE_ACCESS); ClientDetailsEntity client = new ClientDetailsEntity(); client = service.updateClient(oldClient, client); Mockito.verify(scopeService...
public static Object eval(Parameter param, Map<String, Parameter> params) { if (!param.isEvaluated()) { switch (param.getType()) { case STRING: return interpolate(param.asStringParam().getValue(), params); case STRING_ARRAY: return Arrays.stream(param.asStringArrayParam().g...
@Test public void testStringInterpolationJsonError() { Parameter param = StringParameter.builder().name("test").value("test $invalidMap").build(); Map<String, Parameter> params = new LinkedHashMap<>(); params.put( "invalidMap", MapParameter.builder() .evaluatedResult(Collection...
@VisibleForTesting static Map<String, ExternalResourceDriver> externalResourceDriversFromConfig( Configuration config, PluginManager pluginManager) { final Set<String> resourceSet = getExternalResourceSet(config); if (resourceSet.isEmpty()) { return Collections.emptyMap(); ...
@Test public void testFactoryPluginDoesNotExist() { final Configuration config = new Configuration(); final String driverFactoryClassName = TestingExternalResourceDriverFactory.class.getName(); final PluginManager testingPluginManager = new TestingPluginManager(Collections.emptyMap()); ...
@Override public void put(ExecutionGraphInfo executionGraphInfo) throws IOException { final JobID jobId = executionGraphInfo.getJobId(); final ArchivedExecutionGraph archivedExecutionGraph = executionGraphInfo.getArchivedExecutionGraph(); final JobStatus jobStatus = archived...
@Test public void testPut() throws IOException { assertPutJobGraphWithStatus(JobStatus.FINISHED); }
@Override public String toString() { return StringUtils.join(columns, separator); }
@Test public void testToString() { assertEquals("a,b", new SampleMetadata(',', "a", "b").toString()); }
@Override public RateLimiter rateLimiter(final String name) { return rateLimiter(name, getDefaultConfig()); }
@Test @SuppressWarnings("unchecked") public void rateLimiterPositiveWithSupplier() throws Exception { RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config); Supplier<RateLimiterConfig> rateLimiterConfigSupplier = mock(Supplier.class); when(rateLimiterConfigSupplier.get()...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void shouldNotHaveNullInitializerTwoOptionMaterializedOnAggregate() { assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(null, Materialized.as("test"))); }
public void writeTrailingBytes(byte[] value) { if ((value == null) || (value.length == 0)) { throw new IllegalArgumentException("Value cannot be null or have 0 elements"); } encodedArrays.add(value); }
@Test public void testWriteTrailingBytes() { byte[] escapeChars = new byte[] { OrderedCode.ESCAPE1, OrderedCode.NULL_CHARACTER, OrderedCode.SEPARATOR, OrderedCode.ESCAPE2, OrderedCode.INFINITY, OrderedCode.FF_CHARACTER }; byte[] anoth...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithBigInteger() throws SQLException { BigInteger result = BigInteger.valueOf(0L); when(mergeResultSet.getValue(1, BigInteger.class)).thenReturn(result); assertThat(shardingSphereResultSet.getObject(1, BigInteger.class), is(result)); }
@Override public TopicAssignment place( PlacementSpec placement, ClusterDescriber cluster ) throws InvalidReplicationFactorException { RackList rackList = new RackList(random, cluster.usableBrokers()); throwInvalidReplicationFactorIfNonPositive(placement.numReplicas()); t...
@Test public void testRackListAllBrokersFenced() { // ensure we can place N replicas on a rack when the rack has less than N brokers MockRandom random = new MockRandom(); RackList rackList = new RackList(random, Arrays.asList( new UsableBroker(0, Optional.empty(), true), ...
@Override public boolean removeAll(Collection<?> c) { return get(removeAllAsync(c)); }
@Test public void testRemoveAll() { RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple"); set.add(0.1, 1); set.add(0.2, 2); set.add(0.3, 3); Assertions.assertTrue(set.removeAll(Arrays.asList(1, 2))); assertThat(set).containsOnly(3); Assertion...
@Override public int getConnectTimeout() { return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.ConnectTimeout, DEFAULT_CONNECT_TIMEOUT); }
@Test void testGetConnectTimeoutOverride() { clientConfig.set(IClientConfigKey.Keys.ConnectTimeout, 1000); assertEquals(1000, connectionPoolConfig.getConnectTimeout()); }
public static UInstanceOf create(UExpression expression, UTree<?> type) { return new AutoValue_UInstanceOf(expression, type); }
@Test public void equality() { new EqualsTester() .addEqualityGroup( UInstanceOf.create(UFreeIdent.create("o"), UClassIdent.create("java.lang.String"))) .addEqualityGroup( UInstanceOf.create(UFreeIdent.create("o"), UClassIdent.create("java.lang.Integer"))) .testEqua...
@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 testCopyAndClone() { run("copy.feature"); }
public KsqlGenericRecord build( final List<ColumnName> columnNames, final List<Expression> expressions, final LogicalSchema schema, final DataSourceType dataSourceType ) { final List<ColumnName> columns = columnNames.isEmpty() ? implicitColumns(schema) : columnNames; i...
@Test public void shouldBuildWithRowtime() { // Given: final LogicalSchema schema = LogicalSchema.builder() .keyColumn(KEY, SqlTypes.STRING) .valueColumn(COL0, SqlTypes.STRING) .build(); final List<ColumnName> names = ImmutableList.of(SystemColumns.ROWTIME_NAME, KEY, COL0); fin...
@Override public Integer getIntAndRemove(K name) { return null; }
@Test public void testGetIntAndRemove() { assertNull(HEADERS.getIntAndRemove("name1")); }
@Override public short getShort(int index) { checkIndex(index, 2); return _getShort(index); }
@Test public void getShortBoundaryCheck2() { assertThrows(IndexOutOfBoundsException.class, new Executable() { @Override public void execute() { buffer.getShort(buffer.capacity() - 1); } }); }
public static String dealRule(final String content, final MockRequest mockRequest) { String afterDeal = content; String placeHolder = getPlaceholder(content); while (placeHolder != null) { Object generateData = generate(placeHolder, mockRequest); if (Objects.equals(genera...
@Test public void testDealRule() { String dealedContent = GeneratorFactory.dealRule("${phone}", null); assertThat(dealedContent, matchesRegex("^\"1[3-9]\\d{9}\"$")); }
@Override public String execute(CommandContext commandContext, String[] args) { if (ArrayUtils.isEmpty(args)) { return "Please input the index of the method you want to invoke, eg: \r\n select 1"; } Channel channel = commandContext.getRemote(); String message = args[0]; ...
@Test void testInvokeWithNull() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .will...
public long periodBarriersCrossed(long start, long end) { if (start > end) throw new IllegalArgumentException("Start cannot come before end"); long startFloored = getStartOfCurrentPeriodWithGMTOffsetCorrection(start, getTimeZone()); long endFloored = getStartOfCurrentPeriodWithGMTOf...
@Test public void testPeriodBarriersCrossedJustBeforeEnteringDaylightSaving() { RollingCalendar rc = new RollingCalendar(dailyPattern, TimeZone.getTimeZone("CET"), Locale.US); // Sun Mar 26 22:18:38 CEST 2017, GMT offset = +2h long start = 1490559518333L; System.out.println(new Date(...
public ConsumerGroupDescribeResponseData.Member asConsumerGroupDescribeMember( Assignment targetAssignment, TopicsImage topicsImage ) { return new ConsumerGroupDescribeResponseData.Member() .setMemberEpoch(memberEpoch) .setMemberId(memberId) .setAssignment...
@Test public void testAsConsumerGroupDescribeMember() { Uuid topicId1 = Uuid.randomUuid(); Uuid topicId2 = Uuid.randomUuid(); Uuid topicId3 = Uuid.randomUuid(); Uuid topicId4 = Uuid.randomUuid(); MetadataImage metadataImage = new MetadataImageBuilder() .addTopic(t...
public static String getPinyin(char c) { return getEngine().getPinyin(c); }
@Test public void getPinyinTest(){ final String pinyin = PinyinUtil.getPinyin("你好怡", " "); assertEquals("ni hao yi", pinyin); }
public void dropIndex(Bson keys) { delegate.dropIndex(keys); }
@Test void dropIndex() { final var collection = jacksonCollection("simple", Simple.class); collection.createIndex(new BasicDBObject("name", 1)); collection.createIndex(new BasicDBObject("name", 1).append("_id", 1)); assertThat(mongoCollection("simple").listIndexes()).extracting("na...
@VisibleForTesting void validateParentDept(Long id, Long parentId) { if (parentId == null || DeptDO.PARENT_ID_ROOT.equals(parentId)) { return; } // 1. 不能设置自己为父部门 if (Objects.equals(id, parentId)) { throw exception(DEPT_PARENT_ERROR); } // 2. 父部...
@Test public void testValidateParentDept_parentError() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> deptService.validateParentDept(id, id), DEPT_PARENT_ERROR); }
@Override public List<String> getInsertColumns() { List<SQLExpr> columnSQLExprs = ast.getColumns(); if (columnSQLExprs.isEmpty()) { // INSERT INTO ta VALUES (...), without fields clarified return null; } List<String> list = new ArrayList<>(columnSQLExprs.size(...
@Test public void testGetInsertColumns() { //test for no column String sql = "insert into t values (?)"; SQLStatement ast = getSQLStatement(sql); SqlServerInsertRecognizer recognizer = new SqlServerInsertRecognizer(sql, ast); List<String> insertColumns = recognizer.getInser...
@Override public Double getNumber( Object object ) throws KettleValueException { Long timestampAsInteger = getInteger( object ); if ( null != timestampAsInteger ) { return timestampAsInteger.doubleValue(); } else { return null; } }
@Test public void testConvertTimestampToNumber_Null() throws KettleValueException { ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp(); assertNull( valueMetaTimestamp.getNumber( null ) ); }
@Override public void close() { try { restHighLevelClient.close(); } catch (IOException e) { throw new ElasticsearchException("Could not close ES Rest high level client", e); } }
@Test public void should_close_client() throws IOException { underTest.close(); verify(restClient).close(); }
@RequiresApi(Build.VERSION_CODES.R) @Override public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) { final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions(); if (inlineSuggestions.size() > 0) { mInlineSuggestionAction.onNewSuggestions(inline...
@Test public void testPrioritizePinnedSuggestions() { simulateOnStartInputFlow(); var inlineView1 = Mockito.mock(InlineContentView.class); var inlineView2 = Mockito.mock(InlineContentView.class); var inlineView3Pinned = Mockito.mock(InlineContentView.class); var inlineView4 = Mockito.mock(InlineCo...
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldAnonymizeDefineUndefineProperty() { Assert.assertEquals("DEFINE variable='[string]';", anon.anonymize("DEFINE format = 'JSON';")); Assert.assertEquals("UNDEFINE variable;", anon.anonymize("UNDEFINE format;")); }
@Override public V get() throws InterruptedException, ExecutionException { try { return resolve(future.get()); } catch (HazelcastSerializationException e) { throw new ExecutionException(e); } }
@Test public void test_get_whenData_andMultipleTimesInvoked_thenSameInstanceReturned() throws Exception { Object value = "value"; Data data = serializationService.toData(value); Future<Object> future = new DelegatingCompletableFuture<>(serializationService, newCompletedFuture(data)); ...
public void installIntents(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) { // If no any Intents to be uninstalled or installed, ignore it. if (!toUninstall.isPresent() && !toInstall.isPresent()) { return; } // Classify installable Intents to different ins...
@Test public void testUninstallAndInstallIntent() { IntentData toUninstall = new IntentData(createTestIntent(), IntentState.INSTALLED, new WallClockTimestamp()); IntentData toInstall = new IntentData(crea...
@Override public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType) { return get(annotationType, null, null); }
@Test void adaptFromEmptyArrayToAnyComponentType() { AttributeMethods methods = AttributeMethods.forAnnotationType(ArrayTypes.class); Map<String, Object> attributes = new HashMap<>(); for (int i = 0; i < methods.size(); i++) { attributes.put(methods.get(i).getName(), new Object[] {}); } MergedAnnotation<A...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<Path>(); // At least one entry successfully parsed boolean success = false; // Call hook for those im...
@Test public void testParseAbsolutePaths() throws Exception { Path path = new Path( "/data/FTP_pub", EnumSet.of(Path.Type.directory)); String[] replies = new String[]{ "- [RWCEAFMS] Petersm 0 May 05 2004 /data/FTP_pub/WelcomeTo_PeakFTP" }...
public String getTag() { return tag; }
@Override @Test public void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{\"notify\":\"true\"},\"dataId\":\"test_data\",\"group\":\"group\"," + "\"tenant\":\"test_tenant\",\"notify\":true,\"module\":\"config\",\"tag\":\"tag\"}"; ConfigQueryReques...
@Override public List<KsqlPartitionLocation> locate( final List<KsqlKey> keys, final RoutingOptions routingOptions, final RoutingFilterFactory routingFilterFactory, final boolean isRangeScan ) { if (isRangeScan && keys.isEmpty()) { throw new IllegalStateException("Query is range sc...
@Test public void shouldThrowIfMetadataNotAvailable() { // Given: getEmtpyMetadata(); // When: final Exception e = assertThrows( MaterializationException.class, () -> locator.locate(ImmutableList.of(KEY), routingOptions, routingFilterFactoryActive, false) ); // Then: asse...
public static Expression convert(Predicate[] predicates) { Expression expression = Expressions.alwaysTrue(); for (Predicate predicate : predicates) { Expression converted = convert(predicate); Preconditions.checkArgument( converted != null, "Cannot convert Spark predicate to Iceberg expres...
@Test public void testUnsupportedUDFConvert() { ScalarFunction<UTF8String> icebergVersionFunc = (ScalarFunction<UTF8String>) new IcebergVersionFunction().bind(new StructType()); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( icebergVersionFunc.name(), icebergVer...
@Override public ValidationTaskResult validateImpl(Map<String, String> optionMap) { // Skip this test if NOSASL if (mConf.get(PropertyKey.SECURITY_AUTHENTICATION_TYPE) .equals(AuthType.NOSASL)) { return new ValidationTaskResult(ValidationUtils.State.SKIPPED, getName(), String.f...
@Test public void proxyUsersAndGroupsAllMissing() { String userName = System.getProperty("user.name"); // Proxyuser configured for bob, not the running user prepareHdfsConfFiles(ImmutableMap.of("hadoop.proxyuser.bob.users", "user1,user3", "hadoop.proxyuser.bob.groups", "*")); HdfsProxyUs...
public List<T> toList() { List<T> result = new LinkedList<>(); for (int i = 0; i < size; i++) { result.add((T) elements[i]); } return result; }
@Test void testOfferMoreThanSizeWithShuffle() { List<Integer> testCase = new ArrayList<>(50); for (int i = 0; i < 50; i++) { testCase.add(i); } Collections.shuffle(testCase); FixedSizePriorityQueue<Integer> queue = new FixedSizePriorityQueue<>(10, Comparator.<Inte...
public static int[] toIntArray(Collection<Integer> collection) { int[] collectionArray = new int[collection.size()]; int index = 0; for (Integer item : collection) { collectionArray[index++] = item; } return collectionArray; }
@Test(expected = NullPointerException.class) public void testToIntArray_whenNull_thenThrowNPE() { toIntArray(null); }
@Override public void loadConfiguration(NacosLoggingProperties loggingProperties) { String location = loggingProperties.getLocation(); configurator.setLoggingProperties(loggingProperties); LoggerContext loggerContext = loadConfigurationOnStart(location); if (hasNoListener(loggerConte...
@Test void testLoadConfigurationStop() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask()); logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); ...
public void execute(){ logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages); long startTime = System.currentTimeMillis(); long executionTime = 0; int i = 0; int exceptionsSwallowedCount = 0; int operationsCompleted =...
@Test(timeout = 1000L) public void execute_emptypage(){ CountingPageOperation op = new EmptyPageCountingPageOperation(Integer.MAX_VALUE, Long.MAX_VALUE); op.execute(); assertEquals(0L, op.getCounter()); }
@Override public void execute(ComputationStep.Context context) { new DepthTraversalTypeAwareCrawler( new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) { @Override public void visitProject(Component project) { executeForProject(project); } }).visit(tree...
@Test void mutableQualityGateStatusHolder_is_not_populated_if_there_is_no_qualitygate() { qualityGateHolder.setQualityGate(null); underTest.execute(new TestComputationStepContext()); assertThatThrownBy(() -> qualityGateStatusHolder.getStatus()) .isInstanceOf(IllegalStateException.class) .has...
public HollowHashIndexResult findMatches(Object... query) { if (hashStateVolatile == null) { throw new IllegalStateException(this + " wasn't initialized"); } int hashCode = 0; for(int i=0;i<query.length;i++) { if(query[i] == null) throw new Illega...
@Test public void testIndexingStringTypeFieldWithNullValues() throws Exception { mapper.add(new TypeB(null)); mapper.add(new TypeB("onez:")); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeB", "", "b1.value"); Assert.assertNull(index....
public void print(final ByteBuffer encodedMessage, final StringBuilder output) { final UnsafeBuffer buffer = new UnsafeBuffer(encodedMessage); print(output, buffer, 0); }
@Test void exampleMessagePrintedAsJson() throws Exception { final ByteBuffer encodedSchemaBuffer = ByteBuffer.allocate(SCHEMA_BUFFER_CAPACITY); encodeSchema(encodedSchemaBuffer); final ByteBuffer encodedMsgBuffer = ByteBuffer.allocate(MSG_BUFFER_CAPACITY); encodeTestMessage(enco...
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldBuildAssertSchemaWithSubject() { // Given: final SingleStatementContext stmt = givenQuery("ASSERT SCHEMA SUBJECT X;"); // When: final AssertSchema assertSchema = (AssertSchema) builder.buildStatement(stmt); // Then: assertThat(assertSchema.getSubject(), is(Opt...
@Override public void run() { JobConfig jobConfig = null; Serializable taskArgs = null; try { jobConfig = (JobConfig) SerializationUtils.deserialize( mRunTaskCommand.getJobConfig().toByteArray()); if (mRunTaskCommand.hasTaskArgs()) { taskArgs = SerializationUtils.deserialize(...
@Test public void runFailure() throws Exception { long jobId = 1; long taskId = 2; JobConfig jobConfig = new SleepJobConfig(10); Serializable taskArgs = Lists.newArrayList(1); RunTaskContext context = mock(RunTaskContext.class); @SuppressWarnings("unchecked") PlanDefinition<JobConfig, Seri...
public String route(final ReadwriteSplittingDataSourceGroupRule rule) { return rule.getLoadBalancer().getTargetName(rule.getName(), getFilteredReadDataSources(rule)); }
@Test void assertRouteWithFilter() { rule.disableDataSource("read_ds_0"); assertThat(new StandardReadwriteSplittingDataSourceRouter().route(rule), is("read_ds_1")); }
@Override public List<MetricFamilySamples> collect() { List<MetricFamilySamples> result = new ArrayList<>(); result.addAll(clientTotal.collect()); result.addAll(clientFail.collect()); result.addAll(serverTotal.collect()); result.addAll(serverFail.collect()); result.ad...
@Test public void testPrometheusMetricsCollect2() throws Exception { MetricsBuilder metricsBuilder = new MetricsBuilder(); // set buckets metricsBuilder.getClientTotalBuilder() .exponentialBuckets(1, 2, 15); metricsBuilder.getClientFailBuilder() .linea...
public static boolean pathIsFromNamespace(String path) { return path.startsWith(BASE_POLICIES_PATH + "/") && path.substring(BASE_POLICIES_PATH.length() + 1).contains("/"); }
@Test public void test_pathIsFromNamespace() { assertFalse(NamespaceResources.pathIsFromNamespace("/admin/clusters")); assertFalse(NamespaceResources.pathIsFromNamespace("/admin/policies")); assertFalse(NamespaceResources.pathIsFromNamespace("/admin/policies/my-tenant")); assertTrue(...
public Authentication getAuthentication(String token) throws AccessException { if (!tokenMap.containsKey(token)) { return jwtTokenManager.getAuthentication(token); } return tokenMap.get(token).getAuthentication(); }
@Test void testGetAuthentication() throws AccessException { assertNotNull(cachedJwtTokenManager.getAuthentication("token")); }
public static <K, E> Collector<E, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) { return unorderedIndex(keyFunction, Function.identity()); }
@Test public void unorderedIndex_returns_SetMultimap() { SetMultimap<Integer, MyObj> multimap = LIST.stream().collect(unorderedIndex(MyObj::getId)); assertThat(multimap.size()).isEqualTo(3); Map<Integer, Collection<MyObj>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly(MY_OBJ_1_A); a...
public Long getValue(final List<Object> params) { return getValueFromExpression(expressionSegment, params); }
@Test void assertGetValueWithMixed() { ExpressionRowNumberValueSegment actual = new ExpressionRowNumberValueSegment(0, 0, new BinaryOperationExpression(0, 0, new LiteralExpressionSegment(0, 0, 1), new BinaryOperationExpression(0, 0, new ParameterMarkerExpressionSegment(0, 0, 0), new LiteralE...
@Override public READ3Response read(XDR xdr, RpcInfo info) { return read(xdr, getSecurityHandler(info), info.remoteAddress()); }
@Test(timeout = 60000) public void testRead() throws Exception { HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar"); long dirId = status.getFileId(); int namenodeId = Nfs3Utils.getNamenodeId(config); FileHandle handle = new FileHandle(dirId, namenodeId); READ3Request readReq = new ...
@Nonnull public static String uppercaseFirstChar(@Nonnull String name) { int len = name.length(); if (len == 1) return name.toUpperCase(); else if (len > 1) return name.substring(0, 1).toUpperCase() + name.substring(1); else return name; }
@Test void testUppercaseFirstChar() { assertEquals("", StringUtil.uppercaseFirstChar("")); assertEquals("F", StringUtil.uppercaseFirstChar("f")); assertEquals("Foo", StringUtil.uppercaseFirstChar("foo")); assertEquals("FOO", StringUtil.uppercaseFirstChar("fOO")); }
public void schedule(BeanContainer container, String id, String cron, String interval, String zoneId, String className, String methodName, List<JobParameter> parameterList) { JobScheduler scheduler = container.beanInstance(JobScheduler.class); String jobId = getId(id); String optionalCronExpress...
@Test void beansWithMethodsAnnotatedWithRecurringAnnotationCronAndIntervalWillThrowException() { final String id = "my-job-id"; final JobDetails jobDetails = jobDetails().build(); final String cron = "*/15 * * * *"; final String interval = "PT10M"; final String zoneId = null;...
public UiTopoOverlayFactory topoOverlayFactory() { return topoOverlayFactory; }
@Test public void topoOverlayFactory() { viewList = ImmutableList.of(HIDDEN_VIEW); ext = new UiExtension.Builder(cl, viewList) .topoOverlayFactory(TO_FACTORY) .build(); assertNull("unexpected message handler factory", ext.messageHandlerFactory()); ass...
public static String getEffectivePath(String path, int port) { return path.replace("_PORT", String.valueOf(port)); }
@Test(timeout=180000) public void testSocketPathSetGet() throws IOException { Assert.assertEquals("/var/run/hdfs/sock.100", DomainSocket.getEffectivePath("/var/run/hdfs/sock._PORT", 100)); }
@Override public Class<? extends AvgPercentileFunctionBuilder> builder() { return AvgPercentileFunctionBuilder.class; }
@Test public void testBuilder() throws IllegalAccessException, InstantiationException { PercentileFunctionInst inst = new PercentileFunctionInst(); inst.accept( MeterEntity.newService("service-test", Layer.GENERAL), new PercentileArgument( new BucketedValues( ...
protected FEEL newFeelEvaluator(AtomicReference<FEELEvent> errorHolder) { // cleanup existing error errorHolder.set(null); FEEL feel = FEELBuilder.builder().withProfiles(singletonList(new ExtendedDMNProfile())).build(); feel.addListener(event -> { FEELEvent feelEvent = errorH...
@Test public void listener_sintaxErrorAsFirst() { FEELEvent syntaxErrorEvent = new SyntaxErrorEvent(Severity.ERROR, "test", null, 0, 0, null); FEELEvent genericError = new FEELEventBase(Severity.ERROR, "error", null); AtomicReference<FEELEvent> error = new AtomicReference<>(); FEEL f...
public boolean checkFeExistByRPCPort(String host, int rpcPort) { try { tryLock(true); return frontends .values() .stream() .anyMatch(fe -> fe.getHost().equals(host) && fe.getRpcPort() == rpcPort); } finally { ...
@Test public void testCheckFeExistByRpcPort() { NodeMgr nodeMgr = new NodeMgr(); Frontend fe = new Frontend(FrontendNodeType.FOLLOWER, "node1", "10.0.0.3", 9010); fe.handleHbResponse(new FrontendHbResponse("node1", 9030, 9020, 1, System.currentTimeMillis(), System.currentTime...
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { String path = ((HttpServletRequest) req).getRequestURI().replaceFirst(((HttpServletRequest) req).getContextPath(), ""); MAX_AGE_BY_PATH.entrySet().stream() .filter(m -> pat...
@Test public void max_age_is_set_to_five_minutes_on_images() throws Exception { HttpServletRequest request = newRequest("/images/logo.png"); underTest.doFilter(request, response, chain); verify(response).addHeader("Cache-Control", format("max-age=%s", 300)); }
public void convert(FSConfigToCSConfigConverterParams params) throws Exception { validateParams(params); this.clusterResource = getClusterResource(params); this.convertPlacementRules = params.isConvertPlacementRules(); this.outputDirectory = params.getOutputDirectory(); this.rulesToFile = para...
@Test public void testInvalidFairSchedulerXml() throws Exception { FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder() .withClusterResource(CLUSTER_RESOURCE_STRING) .withFairSchedulerXmlConfig(FAIR_SCHEDULER_XML_INVALID) .build(); expectedException.expect(RuntimeEx...
public static boolean isEmpty(CharSequence str) { return str == null || str.length() == 0; }
@Test public void assertIsEmpty() { String string = ""; Assert.assertTrue(StringUtil.isEmpty(string)); }
public ServiceResponse getServiceConfigGeneration(Application application, String hostAndPortToCheck, Duration timeout) { Long wantedGeneration = application.getApplicationGeneration(); try (CloseableHttpAsyncClient client = createHttpClient()) { client.start(); if ( ! hostInAppl...
@Test public void service_convergence() { { // Known service wireMock.stubFor(get(urlEqualTo("/state/v1/config")).willReturn(okJson("{\"config\":{\"generation\":3}}"))); ServiceResponse response = checker.getServiceConfigGeneration(application, hostAndPort(this.service), clientTimeo...
public Date parseString(String dateString) throws ParseException { if (dateString == null || dateString.isEmpty()) { return null; } Matcher xep82WoMillisMatcher = xep80DateTimeWoMillisPattern.matcher(dateString); Matcher xep82Matcher = xep80DateTimePattern.matcher(dateString)...
@Test public void testFormatThreeSecondFractions() throws Exception { // Setup fixture final String testValue = "2015-03-19T22:54:15.841+00:00"; // Thu, 19 Mar 2015 22:54:15.841 GMT // Execute system under test final Date result = xmppDateTimeFormat.parseString(testValue); ...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Disabled("dropped since DMNv1.2") @Test void functionDecisionTableInvocation() { String inputExpression = "decision table( " + " outputs: \"Applicant Risk Rating\"," + " input expression list: [\"Applicant Age\", \"Medical History\...
@Override public boolean hasNext() { try { if (this.nextElement == null) { if (this.readPhase) { // read phase, get next element from buffer T tmp = getNextRecord(this.reuseElement); if (tmp != null) { ...
@Test void testDoubleBufferedBlockResettableIterator() throws Exception { final AbstractInvokable memOwner = new DummyInvokable(); // create the resettable Iterator final ReusingBlockResettableIterator<Record> iterator = new ReusingBlockResettableIterator<Record>( ...
public String error(Message errorMessage, Locale locale) { var localizedErrorMessage = formatLocalizedErrorMessage(errorMessage, locale); return renderer.render( "error.html.mustache", Map.of("errorMessage", localizedErrorMessage), locale); }
@Test void error_withFixture() { var sut = new Pages(renderer); var rendered = sut.error(new Message("error.serverError", ""), Locale.US); assertEquals(Fixtures.getUtf8String("pages_golden_error.bin"), rendered); }
@Override public boolean userDefinedIndexMode(boolean enable) { if (meters.isEmpty() && meterIdGenerators.isEmpty()) { userDefinedIndexMode = enable; } else { log.warn("Unable to {} user defined index mode as store did" + "already some allocations", enable...
@Test public void testEnableUserDefinedIndex() { initMeterStore(false); assertTrue(meterStore.userDefinedIndexMode(true)); }