focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Collection<JID> getAdmins() { return administrators; }
@Test public void testReflectedInCacheGroupDeleted() throws Exception { // Setup test fixture. final String groupName = "unit-test-group-p"; final Group group = groupManager.createGroup(groupName); final JID testUser = new JID("unit-test-user-p", "example.org", null); gro...
@Udf(description = "Converts a TIMESTAMP value into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'" + " The system default time zone is used when no time zone is explicitly ...
@Test public void shouldThrowIfFormatInvalid() { // When: final KsqlException e = assertThrows( KsqlFunctionException.class, () -> udf.formatTimestamp(new Timestamp(1638360611123L), "invalid") ); // Then: assertThat(e.getMessage(), containsString("Unknown pattern letter: i")); }
@Override public void clear() { complete(treeMap.clear()); }
@Test public void testClear() { treeMap.clear(); assertThat(treeMap.size(), is(0)); }
void validateAttributesField(Schema schema) { String attributesKeyName = getAttributesKeyName(); if (!schema.hasField(attributesKeyName)) { return; } checkArgument( SchemaReflection.of(schema) .matchesAll(FieldMatcher.of(attributesKeyName, ATTRIBUTES_FIELD_TYPE))); }
@Test public void testValidateAttributesField() { PubsubRowToMessage pubsubRowToMessage = PubsubRowToMessage.builder().build(); pubsubRowToMessage.validateAttributesField(ALL_DATA_TYPES_SCHEMA); pubsubRowToMessage.validateAttributesField( Schema.of(Field.of(DEFAULT_ATTRIBUTES_KEY_NAME, ATTRIBUTES_...
@Transactional public ServerConfig createOrUpdateConfig(ServerConfig serverConfig) { ServerConfig storedConfig = serverConfigRepository.findByKey(serverConfig.getKey()); if (Objects.isNull(storedConfig)) {//create serverConfig.setId(0L);//为空,设置ID 为0,jpa执行新增操作 if(Objects.isNull(serverConfig.getCl...
@Test public void createOrUpdateConfig() { ServerConfig serverConfig = new ServerConfig(); serverConfig.setKey("name"); serverConfig.setValue("kl"); serverConfigService.createOrUpdateConfig(serverConfig); List<ServerConfig> serverConfigs = serverConfigService.findAll(); assertThat(serverConfi...
public final synchronized void setStreamsConfig(final StreamsConfig applicationConfig) { Objects.requireNonNull(applicationConfig, "config can't be null"); topologyConfigs = new TopologyConfig(applicationConfig); }
@Test public void shouldNotSetStreamsConfigToNull() { assertThrows(NullPointerException.class, () -> builder.setStreamsConfig(null)); }
public long getSignature() { return this.signature; }
@Test public void toThriftTest() throws Exception { Class<? extends AgentBatchTask> agentBatchTaskClass = agentBatchTask.getClass(); Class[] typeParams = new Class[] {AgentTask.class}; Method toAgentTaskRequest = agentBatchTaskClass.getDeclaredMethod("toAgentTaskRequest", typeParams); ...
@Override public HttpHeaders filter(HttpHeaders headers, ServerWebExchange exchange) { HttpHeaders updated = new HttpHeaders(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { updated.addAll(entry.getKey(), entry.getValue()); } // https://datatracker.ietf.org/doc/html/rfc7540#section-8....
@Test public void shouldNotIncludeTrailersHeaderIfNotGRPC() { MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost:8080/get") .header(HttpHeaders.CONTENT_TYPE, "application/json") .build(); GRPCRequestHeadersFilter filter = new GRPCRequestHeadersFilter(); HttpHeaders headers = filt...
@Override public byte[] toByteArray() { return toByteArray(0); }
@Test(expected = UnsupportedOperationException.class) public void testToByteArray() throws Exception { dataOutputStream.toByteArray(); }
@Override protected boolean isStepCompleted(@NonNull Context context) { return SetupSupport.isThisKeyboardSetAsDefaultIME(context); }
@Test public void testKeyboardEnabledAndDefault() { final String flatASKComponent = new ComponentName(BuildConfig.APPLICATION_ID, SoftKeyboard.class.getName()) .flattenToString(); Settings.Secure.putString( getApplicationContext().getContentResolver(), Settings.Secure.ENABL...
public static ParameterTool fromPropertiesFile(String path) throws IOException { File propertiesFile = new File(path); return fromPropertiesFile(propertiesFile); }
@Test void testFromPropertiesFile(@TempDir File propertiesFile) throws IOException { Properties props = new Properties(); props.setProperty("input", "myInput"); props.setProperty("expectedCount", "15"); Path path = new File(propertiesFile, UUID.randomUUID().toString()).toPath(); ...
@Override public boolean contains(Object o) { for (M member : members) { if (selector.select(member) && o.equals(member)) { return true; } } return false; }
@Test public void testDoesNotContainNonMatchingMemberWhenLiteMembersSelectedAndNoLocalMember() { Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, and(LITE_MEMBER_SELECTOR, NON_LOCAL_MEMBER_SELECTOR)); assertFalse(collection.contains(dataMember)); }
@Override public void updateDictType(DictTypeSaveReqVO updateReqVO) { // 校验自己存在 validateDictTypeExists(updateReqVO.getId()); // 校验字典类型的名字的唯一性 validateDictTypeNameUnique(updateReqVO.getId(), updateReqVO.getName()); // 校验字典类型的类型的唯一性 validateDictTypeUnique(updateReqVO.ge...
@Test public void testUpdateDictType_success() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 准备参数 DictTypeSaveReqVO reqVO = randomPojo(DictTypeSaveReqVO.class, o -> { o.setId(dbDictType.getId());...
@Override public void execute(SensorContext context) { Set<String> reportPaths = loadReportPaths(); Map<String, SarifImportResults> filePathToImportResults = new HashMap<>(); for (String reportPath : reportPaths) { try { SarifImportResults sarifImportResults = processReport(context, reportP...
@Test public void execute_whenImportFails_shouldSkipReport() throws NoSuchFileException { sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM); ReportAndResults reportAndResults1 = mockFailedReportAndResults(FILE_1); ReportAndResults reportAndResults2 = mockSuccessfulReportAndRe...
@Override @SuppressWarnings("deprecation") protected String getAppName() { String appName = registration.getServiceId(); return StringUtils.isEmpty(appName) ? super.getAppName() : appName; }
@Test public void testGetAppName() { doReturn("application").when(environment).getProperty(anyString(), anyString()); assertThat(polarisAutoServiceRegistration.getAppName()).isEqualTo("application"); doReturn(SERVICE_PROVIDER).when(registration).getServiceId(); assertThat(polarisAutoServiceRegistration.getApp...
@Override public int getMemoryFootprint() { return m; }
@Test public void testGetMemoryFootprint() { DenseHyperLogLogEncoder encoder = getDenseHyperLogLogEncoder(); int memoryFootprint = encoder.getMemoryFootprint(); assertEquals(1 << precision(), memoryFootprint); }
private void stop(int numOfServicesStarted, boolean stopOnlyStartedServices) { // stop in reverse order of start Exception firstException = null; List<Service> services = getServices(); for (int i = numOfServicesStarted - 1; i >= 0; i--) { Service service = services.get(i); if (LOG.isDebugEn...
@Test(timeout = 10000) public void testAddStoppedChildInStart() throws Throwable { CompositeService parent = new CompositeService("parent"); BreakableService child = new BreakableService(); child.init(new Configuration()); child.start(); child.stop(); parent.init(new Configuration()); pare...
public static boolean isCollection(Object obj) { return obj instanceof Collection || obj instanceof Map; }
@Test public void isCollection() { assertTrue(CommonUtils.isCollection(Sets.newHashSet())); assertTrue(CommonUtils.isCollection(Maps.newHashMap())); assertTrue(CommonUtils.isCollection(Lists.newArrayList())); assertFalse(CommonUtils.isCollection(null)); assertFalse(CommonUtils.isCollection(1)); ...
@Override public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) { if (!shouldHandle(instances)) { return instances; } List<Object> result = getTargetInstancesByRules(targetName, instances); return super.handle(targetName, result, ...
@Test public void testGetTargetInstancesByTagRulesWithPolicySceneOne() { RuleInitializationUtils.initAZTagMatchTriggerThresholdPolicyRule(); List<Object> instances = new ArrayList<>(); ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0", "az1"); ...
public OpenConfigConfigOfComponentHandler addName(String name) { modelObject.name(name); return this; }
@Test public void testAddName() { // test Handler OpenConfigConfigOfComponentHandler config = new OpenConfigConfigOfComponentHandler(parent); // call addName config.addName("name"); // expected ModelObject DefaultConfig modelObject = new DefaultConfig(); mod...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { boolean satisfied = false; // No trading history, no need to wait if (tradingRecord != null) { Trade lastTrade = tradingRecord.getLastTrade(tradeType); if (lastTrade != null) { ...
@Test public void waitForSinceLastSellRuleIsSatisfied() { // Waits for 2 bars since last sell trade rule = new WaitForRule(Trade.TradeType.SELL, 2); assertFalse(rule.isSatisfied(0, null)); assertFalse(rule.isSatisfied(1, tradingRecord)); tradingRecord.enter(10); ass...
@Produces @DefaultBean @Singleton JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration() { if (jobRunrBuildTimeConfiguration.dashboard().enabled()) { final JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration = usingStandardDashboardConfiguration(); ...
@Test void dashboardWebServerConfigurationIsNotSetupWhenNotConfigured() { when(dashboardBuildTimeConfiguration.enabled()).thenReturn(false); assertThat(jobRunrProducer.dashboardWebServerConfiguration()).isNull(); }
@Override public long getMin() { if (values.length == 0) { return 0; } return values[0]; }
@Test public void calculatesTheMinimumValue() throws Exception { assertThat(snapshot.getMin()) .isEqualTo(1); }
public static <T, R> Callable<R> andThen(Callable<T> callable, Function<T, R> resultHandler) { return () -> resultHandler.apply(callable.call()); }
@Test public void shouldChainCallableAndResultHandler() throws Exception { Callable<String> Callable = () -> "BLA"; Callable<String> callableWithRecovery = CallableUtils.andThen(Callable, result -> "Bla"); String result = callableWithRecovery.call(); assertThat(result).isEqualTo("B...
@Override protected Object createBody() { if (command instanceof MessageRequest) { MessageRequest msgRequest = (MessageRequest) command; byte[] shortMessage = msgRequest.getShortMessage(); if (shortMessage == null || shortMessage.length == 0) { return null...
@Test public void createBodyShouldReturnNullIfTheCommandIsNull() { message = new SmppMessage(camelContext, null, new SmppConfiguration()); assertNull(message.createBody()); }
public void generateAcknowledgementPayload( MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode) throws MllpAcknowledgementGenerationException { generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null); }
@Test public void testGenerateAcknowledgementPayloadFromEmptyMessage() { MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub()); assertThrows(MllpAcknowledgementGenerationException.class, () -> hl7util.generateAcknowledgementPayload(mllpSocketBuffer, new byt...
public boolean containsVertex(V vertex) { return neighbors.containsKey(vertex); }
@Test void containsVertex() { assertTrue(graph.containsVertex('A')); }
public static String[] parseKey(String groupKey) { return groupKey.split(Constants.GROUP_KEY_DELIMITER_TRANSLATION); }
@Test public void parseKey() { String groupKey = "prescription+dynamic-threadpool-example+message-consume+12"; String[] strings = GroupKey.parseKey(groupKey); Assert.isTrue(strings.length == 4); }
public void updatePartitionStatistics(String dbName, String tableName, String partitionName, Function<HivePartitionStats, HivePartitionStats> update) { List<org.apache.hadoop.hive.metastore.api.Partition> partitions = client.getPartitionsByNames( dbName,...
@Test public void testUpdatePartitionStatistics() { HiveMetaClient client = new MockedHiveMetaClient(); HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS); HivePartitionStats partitionStats = HivePartitionStats.empty(); metastore.updatePartitionSta...
public static String getExactlyExpression(final String value) { return Strings.isNullOrEmpty(value) ? value : CharMatcher.anyOf(" ").removeFrom(value); }
@Test void assertGetExactlyExpressionUsingAndReturningNull() { assertNull(SQLUtils.getExactlyExpression(null)); }
Map<ExecNode<?>, Integer> calculateMaximumDistance() { Map<ExecNode<?>, Integer> result = new HashMap<>(); Map<TopologyNode, Integer> inputsVisitedMap = new HashMap<>(); Queue<TopologyNode> queue = new LinkedList<>(); for (TopologyNode node : nodes.values()) { if (node.input...
@Test void testCalculateMaximumDistance() { Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph(); TopologyGraph graph = tuple2.f0; TestingBatchExecNode[] nodes = tuple2.f1; Map<ExecNode<?>, Integer> result = graph.calculateMaximumDistance(); assertThat...
public ParamRequestCondition getMatchingCondition(HttpServletRequest request) { for (ParamExpression expression : this.expressions) { if (!expression.match(request)) { return null; } } return this; }
@Test void testGetMatchingCondition() { MockHttpServletRequest request = new MockHttpServletRequest(); ParamRequestCondition paramRequestCondition1 = paramRequestCondition.getMatchingCondition(request); assertNull(paramRequestCondition1); request.setParameter("test", "1244")...
public static SbeSchema fromIr(Ir ir, IrOptions irOptions) { ImmutableList<SbeField> sbeFields = IrFieldGenerator.generateFields(ir, irOptions); Ir copy = createIrCopy(ir); return new SbeSchema(SerializableIr.fromIr(copy), irOptions, sbeFields); }
@Test public void testFromIr() throws Exception { Ir ir = getIr(OnlyPrimitives.RESOURCE_PATH); SbeSchema actual = SbeSchema.fromIr(ir, IrOptions.DEFAULT); assertNotNull(actual.getIr()); assertNotSame(ir, actual.getIr()); assertEquals(IrOptions.DEFAULT, actual.getIrOptions()); assertEquals(On...
public abstract void verify(String value);
@Test public void testLongRangeAttribute() { LongRangeAttribute longRangeAttribute = new LongRangeAttribute("long.range.key", true, 10, 20, 15); Assert.assertThrows(RuntimeException.class, () -> longRangeAttribute.verify("")); Assert.assertThrows(RuntimeException.class, () -> longRangeAttrib...
@Override public String[] split(String text) { ArrayList<String> sentences = new ArrayList<>(); // The number of words in the sentence. int len = 0; // Remove any carriage returns etc. text = REGEX_CARRIAGE_RETURN.matcher(text).replaceAll(" "); // We will use oct 0...
@Test public void testSplit() { System.out.println("split"); String text = "THE BIG RIPOFF\n\n" + "Mr. John B. Smith bought www.cheap.com for 1.5 million dollars, " + "i.e. he paid far too much for it.Did he mind? " + "Adam Jones Jr. thinks he didn't. ...
@Override public void storeMappingEntry(Type type, MappingEntry entry) { store.storeMapping(type, entry); }
@Test public void storeMappingEntry() { Mapping m1 = mapping(1, 1); Mapping m2 = mapping(2, 2); Mapping m3 = mapping(3, 3); MappingEntry me1 = new DefaultMappingEntry(m1); MappingEntry me2 = new DefaultMappingEntry(m2); MappingEntry me3 = new DefaultMappingEntry(m3)...
protected void runMigration(SqlMigration migration) { LOGGER.info("Running migration {}", migration); try (final Connection conn = getConnection(); final Transaction tran = new Transaction(conn)) { if (!isEmptyMigration(migration)) { runMigrationStatement(conn, migration); ...
@Test void testMigrationIsNotDoneMoreThanOnce() { final JdbcDataSource dataSource = createH2DataSource("jdbc:h2:mem:/test;DB_CLOSE_DELAY=-1"); final DatabaseCreator databaseCreator = Mockito.spy(new DatabaseCreator(dataSource, H2StorageProvider.class)); assertThatCode(databaseCreator::runMi...
@VisibleForTesting ZonedDateTime parseZoned(final String text, final ZoneId zoneId) { final TemporalAccessor parsed = formatter.parse(text); final ZoneId parsedZone = parsed.query(TemporalQueries.zone()); ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply( ObjectUtils.defaultIfNull(parsedZone...
@Test public void shouldParseFullLocalDateWithPassedInTimeZone() { // Given final String format = "yyyy-MM-dd HH"; final String timestamp = "1605-11-05 10"; // When final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, GMT_3); // Then assertThat(ts, is(sameIn...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, String.valueOf(Path.DELIMITER)); }
@Test public void testList() throws Exception { final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final AttributedList<Path> list = new S3ObjectListService(session, new S3AccessControlListFeature(session)).list(container, ne...
private boolean setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState, ContentService contentService, Condition condition, boolean throwOnFailure) { try { ClusterControll...
@Test public void testRetriesUntilExhaustion() { OrchestratorContext context = OrchestratorContext.createContextForSingleAppOp(clock); for (int i = 0; i < clusterControllers.size(); i++) { int j = i + 1; wire.expect((url, body) -> { assertEquals("h...
public static long toLong(String value) { String[] octets = value.split(":"); if (octets.length > 8) { throw new NumberFormatException("Input string is too big to fit in long: " + value); } long l = 0; for (String octet: octets) { if (octet.length() > 2) {...
@Test public void testToLong() { String dpidStr = "3e:1f:01:fc:72:8c:63:31"; long valid = 0x3e1f01fc728c6331L; long testLong = HexString.toLong(dpidStr); assertEquals(valid, testLong); }
public static void executeWithRetries( final Function function, final RetryBehaviour retryBehaviour ) throws Exception { executeWithRetries(() -> { function.call(); return null; }, retryBehaviour); }
@Test public void shouldRetryAndSucceed() throws Exception { // Given: final AtomicInteger counts = new AtomicInteger(5); final Callable<Object> eventuallySucceeds = () -> { if (counts.decrementAndGet() == 0) { return null; } throw new TestRetriableException("I will never succeed...
@Override public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { final Credentials credentials = authorizationService.validate(); try { if(log.isInfoEnabled()) { log.info(String.format("Attempt authentication with %s", cred...
@Test(expected = LoginCanceledException.class) public void testConnectInvalidAccessToken() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new HubicProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( ...
@Override public Runner get() { if (runner == null) { runner = createRunner(); } return runner; }
@Test void should_create_a_runner() { assertThat(runnerSupplier.get(), is(notNullValue())); }
@Override public boolean dbExists(String dbName) { ConnectorMetadata metadata = metadataOfDb(dbName); return metadata.dbExists(dbName); }
@Test void testDbExists(@Mocked ConnectorMetadata connectorMetadata) { new Expectations() { { connectorMetadata.dbExists("test_db"); result = true; times = 1; } }; CatalogConnectorMetadata catalogConnectorMetadata = new...
@ConstantFunction.List(list = { @ConstantFunction(name = "mod", argTypes = {DECIMALV2, DECIMALV2}, returnType = DECIMALV2), @ConstantFunction(name = "mod", argTypes = {DECIMAL32, DECIMAL32}, returnType = DECIMAL32), @ConstantFunction(name = "mod", argTypes = {DECIMAL64, DECIMAL64}, r...
@Test public void modDecimal() { assertEquals("0", ScalarOperatorFunctions.modDecimal(O_DECIMAL_100, O_DECIMAL_100).getDecimal().toString()); assertEquals("0", ScalarOperatorFunctions.modDecimal(O_DECIMAL32P7S2_100, O_DECIMAL32P7S2_100).getDecimal().toString()); assertEquals(...
@Override public Future<Map<String, String>> listConnectLoggers(Reconciliation reconciliation, String host, int port) { String path = "/admin/loggers/"; LOGGER.debugCr(reconciliation, "Making GET request to {}", path); return HttpClientUtils.withHttpClient(vertx, new HttpClientOptions().setL...
@Test public void testListConnectLoggersWithLevelAndLastModified(Vertx vertx, VertxTestContext context) throws Exception { final HttpServer server = mockApi(vertx, 200, new ObjectMapper().writeValueAsString( Map.of( "org.apache.kafka.connect", Map.of( ...
public static Exception lookupExceptionInCause(Throwable source, Class<? extends Exception>... clazzes) { while (source != null) { for (Class<? extends Exception> clazz : clazzes) { if (clazz.isAssignableFrom(source.getClass())) { return (Exception) source; ...
@Test void givenCause_whenLookupExceptionInCause_thenReturnCause() { assertThat(ExceptionUtil.lookupExceptionInCause(new Exception(cause), RuntimeException.class)).isSameAs(cause); }
public static OutStreamOptions defaults(FileSystemContext context, AlluxioConfiguration alluxioConf) { return new OutStreamOptions(context, alluxioConf); }
@Test public void defaults() throws IOException { AlluxioStorageType alluxioType = AlluxioStorageType.STORE; UnderStorageType ufsType = UnderStorageType.SYNC_PERSIST; mConf.set(PropertyKey.USER_BLOCK_SIZE_BYTES_DEFAULT, "64MB"); mConf.set(PropertyKey.USER_FILE_WRITE_TYPE_DEFAULT, WriteType.CACHE_THROU...
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingJsonRowWithUnknownModTypeAndValueCaptureTypeToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "transactionId", false, "1...
@Override public String addResourceReference(String key, SharedCacheResourceReference ref) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource == null) { // it's not mapped return null; } re...
@Test void testBootstrapping() throws Exception { Map<String, String> initialCachedResources = startStoreWithResources(); int count = initialCachedResources.size(); ApplicationId id = createAppId(1, 1L); // the entries from the cached entries should now exist for (int i = 0; i < count; i++) { ...
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test public void testMergeAclEntriesProvidedDefaultMask() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); List<AclEntry> aclSpec = ...
public String asString() { return this.stream().map(ConfigErrors::asString).collect(Collectors.joining(", ")); }
@Test public void shouldGetAConsolidatedListOfErrorsAsMessage() { AllConfigErrors errors = new AllConfigErrors(); errors.add(error("key1")); errors.add(error("key2")); errors.add(error("key3")); assertThat(errors.asString(), is("error on key1, error on key2, error on key3"));...
@Override public IpAddress allocateIp(String networkId) { IpAddress availableIp = availableIps(networkId).stream() .findFirst().orElse(null); if (availableIp != null) { String ipamId = networkId + "-" + availableIp.toString(); k8sIpamStore.removeAvailableIp(ip...
@Test public void testAllocateIp() { createBasicIpPool(); assertEquals("Number of allocated IPs did not match", 0, target.allocatedIps(NETWORK_ID).size()); assertEquals("Number of available IPs did not match", 2, target.availableIps(NETWORK_ID).size()); ...
@Override public ServerGroup servers() { return cache.get(); }
@Test public void all_up_endpoint_is_up() { NginxHealthClient service = createClient("nginx-health-output-all-up.json"); assertTrue(service.servers().isHealthy("gateway.prod.music.vespa.us-east-2.prod")); }
@Inject public Generator(OnnxRuntime onnx, GeneratorConfig config) { // Set up tokenizer tokenizer = new SentencePieceEmbedder.Builder(config.tokenizerModel().toString()).build(); tokenizerMaxTokens = config.tokenizerMaxTokens(); // Set up encoder encoderInputIdsName = confi...
@Test public void testGenerator() { String vocabPath = "src/test/models/onnx/llm/en.wiki.bpe.vs10000.model"; String encoderModelPath = "src/test/models/onnx/llm/random_encoder.onnx"; String decoderModelPath = "src/test/models/onnx/llm/random_decoder.onnx"; assumeTrue(OnnxRuntime.isRu...
public void ensureIndexTemplate(IndexSet indexSet) { final IndexSetConfig indexSetConfig = indexSet.getConfig(); final String templateName = indexSetConfig.indexTemplateName(); try { var template = buildTemplate(indexSet, indexSetConfig); if (indicesAdapter.ensureIndexTem...
@Test public void ensureIndexTemplate_IfIndexTemplateDoesntExistOnIgnoreIndexTemplateAndFailOnMissingTemplateIsTrue_thenExceptionThrown() { when(indexMappingFactory.createIndexMapping(any())) .thenThrow(new IgnoreIndexTemplate(true, "Reasom", "test", "test-template", ...
public KubernetesConfigOptions.ServiceExposedType getRestServiceExposedType() { return flinkConfig.get(KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE); }
@Test void testGetRestServiceExposedType() { flinkConfig.set( KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE, KubernetesConfigOptions.ServiceExposedType.NodePort); assertThat(kubernetesJobManagerParameters.getRestServiceExposedType()) .isEqualByComp...
@Override @SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:MethodLength"}) protected IdentifiedDataSerializable getConfig() { MapConfig config = new MapConfig(parameters.name); config.setAsyncBackupCount(parameters.asyncBackupCount); config....
@Test public void testDataPersistenceAndTieredStoreConfigTransmittedCorrectly() { MapConfig mapConfig = new MapConfig("my-map"); DataPersistenceConfig dataPersistenceConfig = new DataPersistenceConfig(); dataPersistenceConfig.setEnabled(true); dataPersistenceConfig.setFsync(true); ...
public static Area getArea(String ip) { return AreaUtils.getArea(getAreaId(ip)); }
@Test public void testGetArea_long() throws Exception { // 120.203.123.0|120.203.133.255|360900 long ip = Searcher.checkIP("120.203.123.252"); Area area = IPUtils.getArea(ip); assertEquals("宜春市", area.getName()); }
@Override public SnowflakeTableMetadata loadTableMetadata(SnowflakeIdentifier tableIdentifier) { Preconditions.checkArgument( tableIdentifier.type() == SnowflakeIdentifier.Type.TABLE, "loadTableMetadata requires a TABLE identifier, got '%s'", tableIdentifier); SnowflakeTableMetadata ta...
@Test public void testGetTableMetadataMalformedJson() throws SQLException { when(mockResultSet.next()).thenReturn(true); when(mockResultSet.getString("METADATA")).thenReturn("{\"malformed_no_closing_bracket"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy( () ->...
@Override public void onError(QueryException error) { assert error != null; done.compareAndSet(null, error); }
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void when_onErrorCalledTwice_then_secondIgnored() { initProducer(false); producer.onError(QueryException.error("error1")); producer.onError(QueryException.error("error2")); assertThatThrownBy(iterator::hasNext) ...
@Override public String getVersionId(final Path file) throws BackgroundException { if(StringUtils.isNotBlank(file.attributes().getVersionId())) { if(log.isDebugEnabled()) { log.debug(String.format("Return version %s from attributes for file %s", file.attributes().getVersionId(), ...
@Test public void getFileIdFile() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new...
public void printKsqlEntityList(final List<KsqlEntity> entityList) { switch (outputFormat) { case JSON: printAsJson(entityList); break; case TABULAR: final boolean showStatements = entityList.size() > 1; for (final KsqlEntity ksqlEntity : entityList) { writer()....
@Test public void shouldPrintAssertNotExistsTopicResult() { // Given: final KsqlEntityList entities = new KsqlEntityList(ImmutableList.of( new AssertTopicEntity("statement", "name", false) )); // When: console.printKsqlEntityList(entities); // Then: final String output = terminal...
@Override public void execute(final List<String> args, final PrintWriter terminal) { CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP); if (args.isEmpty()) { terminal.println(restClient.getServerAddress()); return; } else { final String serverAddress = args.get(0); restClient.setS...
@Test public void shouldIdentifyCCloudServer() { // When: command.execute(ImmutableList.of(CCLOUD_SERVER_ADDRESS), terminal); // Then: verify(restClient).setIsCCloudServer(true); }
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfAddressNegativePrefixLengthIPv6() { IpAddress ipAddress; IpPrefix ipPrefix; ipAddress = IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"); ipPrefix = IpPrefix.valueOf(ipAddress, -1)...
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { if (value == null) { return true; } else if (value instanceof Collection) { return isValidCollection((Collection<?>) value); } else if (value instanceof Map) { return ((Ma...
@Test public void testInvalidWithNonMatchingObject() { boolean valid = target.isValid(new Object(), constraintValidatorContext); assertThat(valid).isFalse(); }
@Override @SuppressWarnings("unchecked") public <T> T create(Class<T> extensionClass) { String extensionClassName = extensionClass.getName(); ClassLoader extensionClassLoader = extensionClass.getClassLoader(); if (!cache.containsKey(extensionClassLoader)) { cache.put(extensi...
@Test @SuppressWarnings("unchecked") public void createNewEachTimeFromDifferentClassLoaders() throws Exception { ExtensionFactory extensionFactory = new SingletonExtensionFactory(pluginManager); // Get classpath locations URL[] classpathReferences = getClasspathReferences(); //...
public static <T> void invokeAll(List<Callable<T>> callables, long timeoutMs) throws TimeoutException, ExecutionException { ExecutorService service = Executors.newCachedThreadPool(); try { invokeAll(service, callables, timeoutMs); } finally { service.shutdownNow(); } }
@Test public void invokeAllExceptionAndHang() throws Exception { long start = System.currentTimeMillis(); RuntimeException testException = new RuntimeException("failed"); try { CommonUtils.invokeAll(Arrays.asList( () -> { Thread.sleep(10 * Constants.SECOND_MS); retu...
public Future<Void> migrateFromDeploymentToStrimziPodSets(Deployment deployment, StrimziPodSet podSet) { if (deployment == null) { // Deployment does not exist anymore => no migration needed return Future.succeededFuture(); } else { int depReplicas = deployment.get...
@Test public void testNoMigrationToPodSets(VertxTestContext context) { KafkaConnectMigration migration = new KafkaConnectMigration( RECONCILIATION, CLUSTER, null, null, 1_000L, false, null, ...
@Override public boolean filterPath(Path filePath) { if (getIncludeMatchers().isEmpty() && getExcludeMatchers().isEmpty()) { return false; } // compensate for the fact that Flink paths are slashed final String path = filePath.hasWindowsDrive() ? filePath....
@Test void testSingleStarPattern() { GlobFilePathFilter matcher = new GlobFilePathFilter(Collections.singletonList("*"), Collections.emptyList()); assertThat(matcher.filterPath(new Path("a"))).isFalse(); assertThat(matcher.filterPath(new Path("a/b"))).isTrue(); asser...
@Override public Messages process(Messages messages) { for (final MessageFilter filter : filterRegistry) { for (Message msg : messages) { final String timerName = name(filter.getClass(), "executionTime"); final Timer timer = metricRegistry.timer(timerName); ...
@Test public void testAllFiltersAreBeingRun() { final DummyFilter first = new DummyFilter(10); final DummyFilter second = new DummyFilter(20); final DummyFilter third = new DummyFilter(30); final Set<MessageFilter> filters = ImmutableSet.of(first, second, third); final Messag...
public static void validateMaterializedViewPartitionColumns( SemiTransactionalHiveMetastore metastore, MetastoreContext metastoreContext, Table viewTable, MaterializedViewDefinition viewDefinition) { SchemaTableName viewName = new SchemaTableName(viewTable.get...
@Test public void testValidateMaterializedViewPartitionColumnsOneColumnMatch() { TestingSemiTransactionalHiveMetastore testMetastore = TestingSemiTransactionalHiveMetastore.create(); Column dsColumn = new Column("ds", HIVE_STRING, Optional.empty(), Optional.empty()); Column shipmodeColu...
public JobInformation getJobInformation() throws IOException, ClassNotFoundException { if (jobInformation != null) { return jobInformation; } if (serializedJobInformation instanceof NonOffloaded) { NonOffloaded<JobInformation> jobInformation = (NonOffl...
@Test void testOffLoadedAndNonOffLoadedPayload() throws IOException, ClassNotFoundException { final TaskDeploymentDescriptor taskDeploymentDescriptor = createTaskDeploymentDescriptor( new TaskDeploymentDescriptor.NonOffloaded<>(serializedJobInformation), ...
@Override public ParsedSchema fromConnectSchema(final Schema schema) { // Bug in ProtobufData means `fromConnectSchema` throws on the second invocation if using // default naming. return new ProtobufData(new ProtobufDataConfig(updatedConfigs)) .fromConnectSchema(injectSchemaFullName(schema)); }
@Test public void shouldUsePlainPrimitivesIfNoNullableRepresentationIsSet() { // Given: givenNoNullableRepresentation(); // When: final ParsedSchema schema = schemaTranslator.fromConnectSchema(CONNECT_SCHEMA_WITH_NULLABLE_PRIMITIVES); // Then: assertThat(schema.canonicalString(), is("syntax ...
@Override public Iterable<Measure> getChildrenMeasures(String metric) { validateInputMetric(metric); return () -> internalComponent.getChildren().stream() .map(new ComponentToMeasure(metricRepository.getByKey(metric))) .map(ToMeasureAPI.INSTANCE) .filter(Objects::nonNull) .iterator(); ...
@Test public void get_children_measures_when_one_child_has_no_value() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(10)); // No data on file 2 MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, COMMENT_LINES_KEY); assertThat(underTest.getCh...
public static String optimizeErrorMessage(String msg) { if (msg == null) { return null; } if (SERVER_ID_CONFLICT.matcher(msg).matches()) { // Optimize the error msg when server id conflict msg += "\nThe 'server-id' in the mysql cdc connecto...
@Test public void testOptimizeErrorMessageWhenMissingBinlogPositionInMaster() { assertEquals( "Cannot replicate because the master purged required binary logs. Replicate the missing transactions from elsewhere, or provision a new slave from backup. Consider increasing the master's binary log...
public final long readLong() throws IOException { if (input instanceof RandomAccessFile) { return ((RandomAccessFile) input).readLong(); } else if (input instanceof DataInputStream) { return ((DataInputStream) input).readLong(); } else { throw new UnsupportedO...
@Test public void testReadLong() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(281479271743489l, inStream.readLong()); // first long HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED...
public void dropPipe(DropPipeStmt stmt) throws DdlException { Pipe pipe = null; try { lock.writeLock().lock(); Pair<Long, String> dbAndName = resolvePipeNameUnlock(stmt.getPipeName()); PipeId pipeId = nameToId.get(dbAndName); if (pipeId == null) { ...
@Test public void testExecuteFailed() throws Exception { TaskManager taskManager = GlobalStateMgr.getCurrentState().getTaskManager(); mockRepoExecutor(); // mock execution failed for (boolean retryAll : Lists.newArrayList(true, false)) { final String pipeName = "p3"; ...
@Override public boolean replace(K k, V v1, V v2) { return mInternalMap.replace(new IdentityObject<>(k), v1, v2); }
@Test public void replace() { String x = new String("x"); String x2 = new String("x"); assertNull(mMap.put(x, "x")); assertNull(mMap.replace(x2, "x")); assertEquals(1, mMap.size()); assertEquals("x", mMap.replace(x, "y")); assertFalse(mMap.replace(x, "noreplace", "z")); // shouldn't replac...
public static <T> T invoke(Object obj, Method method, Object... args) { return invoke(false, obj, method, args); }
@Test public void invokeStaticTest(){ // 测试执行普通方法 final String result = MethodHandleUtil.invoke(null, ReflectUtil.getMethod(Duck.class, "getDuck", int.class), 78); assertEquals("Duck 78", result); }
@ScalarFunction @LiteralParameters({"x", "y"}) @Constraint(variable = "y", expression = "min(2147483647, x + 15)") // Color formatting uses 15 characters. Note that if the ansiColorEscape function implementation // changes, this value may be invalidated. @SqlType("varchar(y)") public static Slic...
@Test public void testRenderBoolean() { assertEquals(render(true), toSlice("\u001b[38;5;2m✓\u001b[0m")); assertEquals(render(false), toSlice("\u001b[38;5;1m✗\u001b[0m")); }
public List<List<String>> cells() { return raw; }
@Test void cells_should_have_three_columns_and_two_rows() { List<List<String>> raw = createSimpleTable().cells(); assertEquals(2, raw.size(), "Rows size"); for (List<String> list : raw) { assertEquals(3, list.size(), "Cols size: " + list); } }
public static void main(String[] args) throws SQLException { Forest forest = createForest(); LobSerializer serializer = createLobSerializer(args); executeSerializer(forest, serializer); }
@Test void shouldExecuteWithoutExceptionClob() { assertDoesNotThrow(() -> App.main(new String[]{"CLOB"})); }
public static int parseInt(String number) throws NumberFormatException { if (StrUtil.isBlank(number)) { return 0; } if (StrUtil.startWithIgnoreCase(number, "0x")) { // 0x04表示16进制数 return Integer.parseInt(number.substring(2), 16); } if (StrUtil.containsIgnoreCase(number, "E")) { // 科学计数法忽略支持,科学计数...
@Test public void parseIntTest4() { // -------------------------- Parse failed ----------------------- Assertions.assertNull(NumberUtil.parseInt("abc", null)); assertEquals(456, NumberUtil.parseInt("abc", 456)); // -------------------------- Parse success ----------------------- assertEquals(123, Number...
public void resetMasterFlushOffset(final String brokerAddr, final long masterFlushOffset) throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException { ResetMasterFlushOffsetHeader requestHeader = new ResetMasterFlushOffsetHeader(); ...
@Test public void testResetMasterFlushOffset() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); mqClientAPI.resetMasterFlushOffset(defaultBrokerAddr, 1L); }
@Operation(summary = "force-success", description = "FORCE_TASK_SUCCESS") @Parameters({ @Parameter(name = "id", description = "TASK_INSTANCE_ID", required = true, schema = @Schema(implementation = int.class), example = "12") }) @PostMapping(value = "/{id}/force-success", consumes = {"application...
@Test public void testForceTaskSuccess() { Result mockResult = new Result(); putMsg(mockResult, Status.SUCCESS); when(taskInstanceService.forceTaskSuccess(any(), Mockito.anyLong(), Mockito.anyInt())).thenReturn(mockResult); Result taskResult = taskInstanceV2Controller.forceTaskSuc...
public String getScope() { return (String) context.getRequestAttribute(OidcConfiguration.SCOPE) .or(() -> Optional.ofNullable(configuration.getScope())) .orElse("openid profile email"); }
@Test public void shouldResolveScopeFromDefaultValues() { var webContext = MockWebContext.create(); var oidcConfiguration = new OidcConfiguration(); var oidcConfigurationContext = new OidcConfigurationContext(webContext, oidcConfiguration); var result = oidcConfigurationContext.ge...
public final String getName() { return getEnvironment().getTaskInfo().getTaskNameWithSubtasks(); }
@Test void testTaskAvoidHangingAfterSnapshotStateThrownException() throws Exception { // given: Configured SourceStreamTask with source which fails on checkpoint. Configuration taskManagerConfig = new Configuration(); taskManagerConfig.set(STATE_BACKEND, TestMemoryStateBackendFactory.class.g...
public ExecutorConfig setPoolSize(final int poolSize) { if (poolSize <= 0) { throw new IllegalArgumentException("poolSize must be positive"); } this.poolSize = poolSize; return this; }
@Test(expected = IllegalArgumentException.class) public void shouldNotAcceptZeroCorePoolSize() { new ExecutorConfig().setPoolSize(0); }
public static boolean isEnable() { return EVENT_BUS_ENABLE; }
@Test public void isEnable() throws Exception { Assert.assertEquals(EventBus.isEnable(), RpcConfigs.getBooleanValue(RpcOptions.EVENT_BUS_ENABLE)); }
@Override public void createTimelineSchema(String[] args) { try { Configuration conf = new YarnConfiguration(); LOG.info("Creating database and collections for DocumentStore : {}", DocumentStoreUtils.getStoreVendor(conf)); try(DocumentStoreWriter documentStoreWriter = DocumentStoreF...
@Test public void collectionCreatorTest() { new DocumentStoreCollectionCreator().createTimelineSchema(new String[]{}); }
public static String getDefaultKeyDirectory() { return getDefaultKeyDirectory(System.getProperty("os.name")); }
@Test public void testGetDefaultKeyDirectory() { assertTrue( WalletUtils.getDefaultKeyDirectory("Mac OS X") .endsWith( String.format( "%sLibrary%sEthereum", File.separator, File.separator))); ...
public final int getAndIncrement() { return INDEX_UPDATER.getAndIncrement(this) & Integer.MAX_VALUE; }
@Test void testGetAndIncrement() { int get = i1.getAndIncrement(); assertEquals(0, get); assertEquals(1, i1.get()); get = i2.getAndIncrement(); assertEquals(127, get); assertEquals(128, i2.get()); get = i3.getAndIncrement(); assertEquals(Integer.MAX_...
@Override public FieldValueProvider decode(JsonNode value) { return new MillisecondsSinceEpochJsonValueProvider(value, columnHandle); }
@Test public void testDecode() { tester.assertDecodedAs("33701000", TIME, 33701000); tester.assertDecodedAs("\"33701000\"", TIME, 33701000); tester.assertDecodedAs("33701000", TIME_WITH_TIME_ZONE, packDateTimeWithZone(33701000, UTC_KEY)); tester.assertDecodedAs("\"33701000\"", TI...
void allocateCollectionField( Object object, BeanInjectionInfo beanInjectionInfo, String fieldName ) { BeanInjectionInfo.Property property = getProperty( beanInjectionInfo, fieldName ); String groupName = ( property != null ) ? property.getGroupName() : null; if ( groupName == null ) { return; }...
@Test public void allocateCollectionField_Array() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); MetaBeanLevel1 mbl1 = new MetaBeanLevel1(); mbl1.setSub( new MetaBeanLevel2() ); // should set other field based on this size mb...
public static RemotingCommand createResponseCommand(Class<? extends CommandCustomHeader> classHeader) { return createResponseCommand(RemotingSysResponseCode.SYSTEM_ERROR, "not set any response code", classHeader); }
@Test public void testCreateResponseCommand_FailToCreateCommand() { System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, "2333"); int code = RemotingSysResponseCode.SUCCESS; String remark = "Sample remark"; RemotingCommand cmd = RemotingCommand.createResponseCommand(code, remark...
@Override public void execute() { DeleteItemResponse result = ddbClient.deleteItem(DeleteItemRequest.builder().tableName(determineTableName()) .key(determineKey()).returnValues(determineReturnValues()) .expected(determineUpdateCondition()).build()); addAttributesToRe...
@Test public void execute() { Map<String, AttributeValue> key = new HashMap<>(); key.put("1", AttributeValue.builder().s("Key_1").build()); exchange.getIn().setHeader(Ddb2Constants.KEY, key); Map<String, ExpectedAttributeValue> updateCondition = new HashMap<>(); updateCondit...
@VisibleForTesting void updateConfig( Configuration config, ConfigOption<List<String>> configOption, List<String> newValue) { final List<String> originalValue = config.getOptional(configOption).orElse(Collections.emptyList()); if (hasLocal(originalValue)) { L...
@Test void testUpdateConfig() { List<String> artifactList = Arrays.asList("local:///tmp/artifact1.jar", "s3://my-bucket/artifact2.jar"); Configuration config = new Configuration(); config.set(ArtifactFetchOptions.ARTIFACT_LIST, artifactList); List<String> uploadedArt...
@Override public String toString() { return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); }
@Test void testSetFatigue() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Fatigue.ALERT, model.getFatigue()); var messageFormat = "The giant looks healthy, %s and saturated."; for (final var fatigue : Fatigue.values()) { model.setFatigue(f...