focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static void registerSerializers(Fury fury) { fury.registerSerializer(ArrowTable.class, new ArrowTableSerializer(fury)); fury.registerSerializer(VectorSchemaRoot.class, new VectorSchemaRootSerializer(fury)); }
@Test public void testRegisterArrowSerializer() throws Exception { Fury fury = Fury.builder().withLanguage(Language.JAVA).build(); ClassResolver classResolver = fury.getClassResolver(); ArrowSerializers.registerSerializers(fury); assertEquals(classResolver.getSerializerClass(ArrowTable.class), ArrowTa...
public String getApplicationId() { return applicationId; }
@Test public void testGetApplicationId() { // Test the getApplicationId method assertEquals("AppID", event.getApplicationId()); }
public static void calculateChunkedSumsByteArray(int bytesPerSum, int checksumType, byte[] sums, int sumsOffset, byte[] data, int dataOffset, int dataLength) { nativeComputeChunkedSumsByteArray(bytesPerSum, checksumType, sums, sumsOffset, data, dataOffset, dataLength, "", 0, fals...
@Test public void testCalculateChunkedSumsByteArrayFail() throws ChecksumException { allocateArrayByteBuffers(); fillDataAndInvalidChecksums(); NativeCrc32.calculateChunkedSumsByteArray(bytesPerChecksum, checksumType.id, checksums.array(), checksums.position(), data.array(), data.position(), d...
@Override public Collection<String> childNames() { ArrayList<String> childNames = new ArrayList<>(); for (Integer brokerId : image.brokers().keySet()) { childNames.add(brokerId.toString()); } return childNames; }
@Test public void testChildNames() { assertEquals(Collections.singletonList("1"), NODE.childNames()); }
@VisibleForTesting public ConfigDO validateConfigExists(Long id) { if (id == null) { return null; } ConfigDO config = configMapper.selectById(id); if (config == null) { throw exception(CONFIG_NOT_EXISTS); } return config; }
@Test public void testValidateConfigExists_success() { // mock 数据 ConfigDO dbConfigDO = randomConfigDO(); configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据 // 调用成功 configService.validateConfigExists(dbConfigDO.getId()); }
public Repository connectRepository( RepositoriesMeta repositoriesMeta, String repositoryName, String username, String password ) throws KettleException { RepositoryMeta repositoryMeta = repositoriesMeta.findRepository( repositoryName ); if ( repositoryMeta == null ) { log.logBasic( "I couldn't find the r...
@Test public void testConnectRepository() throws KettleException { TransExecutionConfiguration transExecConf = new TransExecutionConfiguration(); final RepositoriesMeta repositoriesMeta = mock( RepositoriesMeta.class ); final RepositoryMeta repositoryMeta = mock( RepositoryMeta.class ); final Reposito...
public int format(String... args) throws UsageException { CommandLineOptions parameters = processArgs(args); if (parameters.version()) { errWriter.println(versionString()); return 0; } if (parameters.help()) { throw new UsageException(); } JavaFormatterOptions options = ...
@Test public void javadoc() throws Exception { String[] input = { "/**", " * graph", " *", " * graph", " *", " * @param foo lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do" + " eiusmod tempor incididunt ut labore et dolore magna aliqua", " */", ...
public static Schema schemaFromPojoClass( TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) { return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier); }
@Test public void testPrimitiveArray() { Schema schema = POJOUtils.schemaFromPojoClass( new TypeDescriptor<PrimitiveArrayPOJO>() {}, JavaFieldTypeSupplier.INSTANCE); SchemaTestUtils.assertSchemaEquivalent(PRIMITIVE_ARRAY_POJO_SCHEMA, schema); }
public ApplicationBuilder name(String name) { this.name = name; return getThis(); }
@Test void name() { ApplicationBuilder builder = new ApplicationBuilder(); builder.name("app"); Assertions.assertEquals("app", builder.build().getName()); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testMaxPlanningSnapshotCount() throws Exception { appendTwoSnapshots(); // append 3 more snapshots for (int i = 2; i < 5; ++i) { appendSnapshot(i, 2); } ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMEN...
public String getStringHeader(Message in, String header, String defaultValue) { String headerValue = in.getHeader(header, String.class); return ObjectHelper.isNotEmpty(headerValue) ? headerValue : defaultValue; }
@Test public void testGetStringHeaderWithNullValue() { when(in.getHeader(HEADER_METRIC_NAME, String.class)).thenReturn(null); assertThat(okProducer.getStringHeader(in, HEADER_METRIC_NAME, "value"), is("value")); inOrder.verify(in, times(1)).getHeader(HEADER_METRIC_NAME, String.class); ...
@SuppressWarnings("unchecked") public static <T> T[] newArray(Class<?> componentType, int newSize) { return (T[]) Array.newInstance(componentType, newSize); }
@Test public void newArrayTest() { String[] newArray = ArrayUtil.newArray(String.class, 3); assertEquals(3, newArray.length); }
public static MetadataUpdate fromJson(String json) { return JsonUtil.parse(json, MetadataUpdateParser::fromJson); }
@Test public void testSetCurrentViewVersionFromJson() { String action = MetadataUpdateParser.SET_CURRENT_VIEW_VERSION; String json = String.format("{\"action\":\"%s\",\"view-version-id\":23}", action); MetadataUpdate expected = new MetadataUpdate.SetCurrentViewVersion(23); assertEquals(action, expecte...
@Override public Set<OAuth2AccessTokenEntity> getAccessTokensByUserName(String name) { TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_NAME, OAuth2AccessTokenEntity.class); query.setParameter(OAuth2AccessTokenEntity.PARAM_NAME, name); List<OAuth2AccessT...
@Test public void testGetAccessTokensByUserName() { Set<OAuth2AccessTokenEntity> tokens = repository.getAccessTokensByUserName("user1"); assertEquals(2, tokens.size()); assertEquals("user1", tokens.iterator().next().getAuthenticationHolder().getUserAuth().getName()); }
@Override public int hashCode() { return filter.hashCode(); }
@Test public void hash() { assertThat(filter.hashCode()).isEqualTo(filter.hashCode()); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final Optional<String> header = getBearerHeader(requestContext); if (header.isEmpty()) { // no JWT token, we'll fail immediately abortRequest(requestContext); } else { ...
@Test void verifyNoHeaderProvided() throws IOException { final String key = "gTVfiF6A0pB70A3UP1EahpoR6LId9DdNadIkYNygK5Z8lpeJIpw9vN0jZ6fdsfeuV9KIg9gVLkCHIPj6FHW5Q9AvpOoGZO3h"; final JwtTokenAuthFilter validator = new JwtTokenAuthFilter(key); final ContainerRequest mockedRequest = mockRequest...
public DirectoryEntry lookUp( File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); DirectoryEntry result = lookUp(workingDirectory, path, options, 0); if (result == null) { // an intermediate file in the path...
@Test public void testLookup_root() throws IOException { assertExists(lookup("/"), "/", "/"); assertExists(lookup("$"), "$", "$"); }
public List<MetricsPacket> getMetrics(List<VespaService> services, Instant startTime) { MetricsPacket.Builder[] builderArray = getMetricsBuildersAsArray(services, startTime, null); List<MetricsPacket> metricsPackets = new ArrayList<>(builderArray.length); for (int i = 0; i < builderArray.length;...
@Test public void system_metrics_are_added() { VespaService service0 = testServices.get(0); Metrics oldSystemMetrics = service0.getSystemMetrics(); service0.getSystemMetrics().add(new Metric(toMetricId("cpu"), 1)); List<MetricsPacket> packets = metricsManager.getMetrics(testService...
public int tryClaim(final int msgTypeId, final int length) { checkTypeId(msgTypeId); checkMsgLength(length); final AtomicBuffer buffer = this.buffer; final int recordLength = length + HEADER_LENGTH; final int recordIndex = claimCapacity(buffer, recordLength); if (IN...
@Test void tryClaimReturnsIndexAtWhichEncodedMessageStartsAfterPadding() { final int length = 10; final int recordLength = length + HEADER_LENGTH; final int alignedRecordLength = align(recordLength, ALIGNMENT); final long headPosition = 248L; final int padding = 22; ...
public boolean isRunning(Member member) { RpcClient client = RpcClientFactory.getClient(memberClientKey(member)); if (null == client) { return false; } return client.isRunning(); }
@Test void testIsRunningForNonExist() { Member member = new Member(); member.setIp("11.11.11.11"); assertFalse(clusterRpcClientProxy.isRunning(member)); }
@Override public String getName() { return name; }
@Test public void testConstructor_withName() { config = new CardinalityEstimatorConfig("myEstimator"); assertEquals("myEstimator", config.getName()); }
public PickTableLayoutForPredicate pickTableLayoutForPredicate() { return new PickTableLayoutForPredicate(metadata); }
@Test public void eliminateTableScanWhenNoLayoutExist() { tester().assertThat(pickTableLayout.pickTableLayoutForPredicate()) .on(p -> { p.variable("orderstatus", createVarcharType(1)); return p.filter(p.rowExpression("orderstatus = 'G'"), ...
@Subscribe public void onVarbitChanged(VarbitChanged varbitChanged) { if (varbitChanged.getVarpId() == VarPlayer.CANNON_AMMO) { int old = cballsLeft; cballsLeft = varbitChanged.getValue(); if (cballsLeft > old) { cannonBallNotificationSent = false; } if (!cannonBallNotificationSent && cbal...
@Test public void testThresholdNotificationsShouldNotNotify() { when(config.lowWarningThreshold()).thenReturn(0); cannonAmmoChanged.setValue(30); plugin.onVarbitChanged(cannonAmmoChanged); cannonAmmoChanged.setValue(10); plugin.onVarbitChanged(cannonAmmoChanged); verify(notifier, never()).notify(any(Not...
public static <T extends DataflowWorkerHarnessOptions> T createFromSystemProperties( Class<T> harnessOptionsClass) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); T options; if (System.getProperties().containsKey("sdk_pipeline_options")) { // TODO: remove this method of gett...
@Test public void testCreationWithPipelineOptionsFile() throws Exception { File file = tmpFolder.newFile(); String jsonOptions = "{\"options\":{\"numWorkers\":1000}}"; Files.write(Paths.get(file.getPath()), jsonOptions.getBytes(StandardCharsets.UTF_8)); System.getProperties() .putAll( ...
@ExecuteOn(TaskExecutors.IO) @Post(uri = "/export/by-ids", produces = MediaType.APPLICATION_OCTET_STREAM) @Operation( tags = {"Flows"}, summary = "Export flows as a ZIP archive of yaml sources." ) public HttpResponse<byte[]> exportByIds( @Parameter(description = "A list of tuple ...
@Test void exportByIds() throws IOException { List<IdWithNamespace> ids = List.of( new IdWithNamespace("io.kestra.tests", "each-object"), new IdWithNamespace("io.kestra.tests", "webhook"), new IdWithNamespace("io.kestra.tests", "task-flow")); byte[] zip = client.t...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String targetObjectId = reader.readLine(); String methodName = reader.readLine(); List<Object> arguments = getArguments(reader); ReturnObject returnObject = invokeMethod(metho...
@Test public void testMethodWithNull() { String inputCommand = target + "\nmethod2\nn\ne\n"; try { command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); inputCommand = target + "\nmethod4\nn\ne\n"; command.execute("c", new Buffered...
@Override public long findConfigMaxId() { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); MapperResult mapperResult = configInfoMapper.findConfigMaxId(null); return Optional.ofNullable(databaseOpe...
@Test void testFindConfigMaxId0() { Mockito.when(databaseOperate.queryOne(anyString(), eq(Long.class))).thenReturn(0L); long configMaxId = embeddedConfigInfoPersistService.findConfigMaxId(); assertEquals(0, configMaxId); }
@Override public CompletableFuture<KubernetesWorkerNode> requestResource( TaskExecutorProcessSpec taskExecutorProcessSpec) { final KubernetesTaskManagerParameters parameters = createKubernetesTaskManagerParameters( taskExecutorProcessSpec, getBlockedNodeRe...
@Test void testOnPodAdded() throws Exception { new Context() { { final CompletableFuture<KubernetesPod> createPodFuture = new CompletableFuture<>(); final CompletableFuture<KubernetesWorkerNode> requestResourceFuture = new CompletableFuture...
public static String format(double amount, boolean isUseTraditional) { return format(amount, isUseTraditional, false); }
@Test public void formatTest2() { String f1 = NumberChineseFormatter.format(-0.3, false, false); assertEquals("负零点三", f1); f1 = NumberChineseFormatter.format(10, false, false); assertEquals("一十", f1); }
public static Collection subtract(final Collection a, final Collection b) { ArrayList list = new ArrayList(a); for (Iterator it = b.iterator(); it.hasNext(); ) { list.remove(it.next()); } return list; }
@Test void testSubtract() { List<String> subtract = (List<String>) CollectionUtils.subtract(Arrays.asList("a", "b"), Arrays.asList("b", "c")); assertEquals(1, subtract.size()); assertEquals("a", subtract.get(0)); }
@Override public Object decorate(RequestedField field, Object value, SearchUser searchUser) { try { final Node node = nodeService.byNodeId(value.toString()); return node.getTitle(); } catch (NodeNotFoundException e) { return value; } }
@Test void decorate() { final Object decorated = decorator.decorate(RequestedField.parse(Message.FIELD_GL2_SOURCE_NODE), "5ca1ab1e-0000-4000-a000-000000000000", TestSearchUser.builder().build()); Assertions.assertThat(decorated).isEqualTo("5ca1ab1e / my-host.example....
public ConfigCheckResult checkConfig() { Optional<Long> appId = getAppId(); if (appId.isEmpty()) { return failedApplicationStatus(INVALID_APP_ID_STATUS); } GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDe...
@Test public void checkConfig_whenAppIdNotValid_shouldReturnFailedAppCheck() { when(gitHubSettings.appId()).thenReturn("not a number"); ConfigCheckResult checkResult = configValidator.checkConfig(); assertThat(checkResult.application().autoProvisioning()).isEqualTo(ConfigStatus.failed(INVALID_APP_ID_STA...
@NonNull public static synchronized ArrayList<String> getAllLogLinesList() { ArrayList<String> lines = new ArrayList<>(msLogs.length); if (msLogs.length > 0) { int index = msLogIndex; do { index--; if (index == -1) index = msLogs.length - 1; String logLine = msLogs[index]; ...
@Test public void testGetAllLogLinesList() throws Exception { // filling up the log buffer for (int i = 0; i < 1024; i++) Logger.d("t", "t"); final int initialListSize = Logger.getAllLogLinesList().size(); // 225 is the max lines count Assert.assertEquals(255, initialListSize); Logger.d("mT...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() != ChatMessageType.SPAM) { return; } var message = event.getMessage(); if (FISHING_CATCH_REGEX.matcher(message).find()) { session.setLastFishCaught(Instant.now()); spotOverlay.setHidden(false); fishingSpotMinimapOve...
@Test public void testKarambwanji() { ChatMessage chatMessage = new ChatMessage(); chatMessage.setType(ChatMessageType.SPAM); chatMessage.setMessage("You catch 15 Karambwanji."); fishingPlugin.onChatMessage(chatMessage); assertNotNull(fishingPlugin.getSession().getLastFishCaught()); }
public static CompletableFuture<Void> runAfterwards( CompletableFuture<?> future, RunnableWithException runnable) { return runAfterwardsAsync(future, runnable, Executors.directExecutor()); }
@Test void testRunAfterwards() { final CompletableFuture<Void> inputFuture = new CompletableFuture<>(); final OneShotLatch runnableLatch = new OneShotLatch(); final CompletableFuture<Void> runFuture = FutureUtils.runAfterwards(inputFuture, runnableLatch::trigger); a...
Path getSelectorFile(DescriptorDigest selector) { return cacheDirectory.resolve(SELECTORS_DIRECTORY).resolve(selector.getHash()); }
@Test public void testGetSelectorFile() throws DigestException { DescriptorDigest selector = DescriptorDigest.fromHash( "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"); Assert.assertEquals( Paths.get( "cache", "directory", "s...
public boolean add(final UUID accountUuid, final byte[] challengeToken, final Duration ttl) { try { db().putItem(PutItemRequest.builder() .tableName(tableName) .item(Map.of( KEY_ACCOUNT_UUID, AttributeValues.fromUUID(accountUuid), ATTR_CHALLENGE_TOKEN, Attribute...
@Test void add() { final UUID uuid = UUID.randomUUID(); assertTrue(pushChallengeDynamoDb.add(uuid, generateRandomToken(), Duration.ofMinutes(1))); assertFalse(pushChallengeDynamoDb.add(uuid, generateRandomToken(), Duration.ofMinutes(1))); }
@Override public Page<ConfigInfo> findConfigInfoLike4Page(final int pageNo, final int pageSize, final String dataId, final String group, final String tenant, final Map<String, Object> configAdvanceInfo) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; final ...
@Test void testFindConfigInfoLike4PageWithTags() { String appName = "appName1234"; String content = "content123"; Map<String, Object> configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("appName", appName); configAdvanceInfo.put("content", content); co...
@Override public PageResult<OperateLogDO> getOperateLogPage(OperateLogPageReqVO pageReqVO) { return operateLogMapper.selectPage(pageReqVO); }
@Test public void testGetOperateLogPage_dto() { // 构造操作日志 OperateLogDO operateLogDO = RandomUtils.randomPojo(OperateLogDO.class, o -> { o.setUserId(2048L); o.setBizId(999L); o.setType("订单"); }); operateLogMapper.insert(operateLogDO); // 测试 ...
@Override public Iterator<QueryableEntry> iterator() { return new It(); }
@Test public void testIterator_empty_next() { assertNull(result.iterator().next()); }
@SuppressWarnings("unchecked") public static <T> T initialize(Map<String, String> properties) { String factoryImpl = PropertyUtil.propertyAsString(properties, S3FileIOProperties.CLIENT_FACTORY, null); if (Strings.isNullOrEmpty(factoryImpl)) { return (T) AwsClientFactories.from(properties); }...
@Test public void testS3FileIOImplCatalogPropertyNotDefined() { // don't set anything Map<String, String> properties = Maps.newHashMap(); Object factoryImpl = S3FileIOAwsClientFactories.initialize(properties); assertThat(factoryImpl) .as( "should instantiate an object of type AwsCl...
public void track(JobID jobId, BlobKey blobKey, long size) { checkNotNull(jobId); checkNotNull(blobKey); checkArgument(size >= 0); synchronized (lock) { if (caches.putIfAbsent(Tuple2.of(jobId, blobKey), size) == null) { blobKeyByJob.computeIfAbsent(jobId, ign...
@Test void testTrack() { assertThat(tracker.getSize(jobId, blobKey)).isEqualTo(3L); assertThat(tracker.getBlobKeysByJobId(jobId)).contains(blobKey); }
@Override public Processor<K, SubscriptionResponseWrapper<VO>, K, VR> get() { return new ContextualProcessor<K, SubscriptionResponseWrapper<VO>, K, VR>() { private String valueHashSerdePseudoTopic; private Serializer<V> runtimeValueSerializer = constructionTimeValueSerializer; ...
@Test public void shouldEmitTombstoneForLeftJoinWhenRightIsNullAndLeftIsNull() { final TestKTableValueGetterSupplier<String, String> valueGetterSupplier = new TestKTableValueGetterSupplier<>(); final boolean leftJoin = true; final ResponseJoinProcessorSupplier<String, String, Str...
public void addAll(Credentials other) { addAll(other, true); }
@Test public void addAll() { Credentials creds = new Credentials(); creds.addToken(service[0], token[0]); creds.addToken(service[1], token[1]); creds.addSecretKey(secret[0], secret[0].getBytes()); creds.addSecretKey(secret[1], secret[1].getBytes()); Credentials credsToAdd = new Credentials();...
public String convert(ILoggingEvent le) { long timestamp = le.getTimeStamp(); return cachingDateFormatter.format(timestamp); }
@Test public void convertsDateAsIso8601WhenNull() { assertEquals(_isoDateString, convert(_timestamp, new String[]{null})); }
static CommandLineOptions parse(Iterable<String> options) { CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); List<String> expandedOptions = new ArrayList<>(); expandParamsFiles(options, expandedOptions); Iterator<String> it = expandedOptions.iterator(); while (it.hasNext()) ...
@Test public void hello() { CommandLineOptions options = CommandLineOptionsParser.parse( Arrays.asList("-lines=1:10,20:30", "-i", "Hello.java", "Goodbye.java")); assertThat(options.lines().asRanges()) .containsExactly(Range.closedOpen(0, 10), Range.closedOpen(19, 30)); assertTh...
public static List<String> listMatchedFilesWithRecursiveOption(PinotFS pinotFs, URI fileUri, @Nullable String includePattern, @Nullable String excludePattern, boolean searchRecursively) throws Exception { String[] files; // listFiles throws IOException files = pinotFs.listFiles(fileUri, searchRe...
@Test public void testMatchFilesRecursiveSearchOnNonRecursiveInputFilePattern() throws Exception { File testDir = makeTestDir(); File inputDir = new File(testDir, "dir"); File inputSubDir1 = new File(inputDir, "2009"); inputSubDir1.mkdirs(); File inputFile1 = new File(inputDir, "input.csv")...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STAT...
@Test public void compositedKeyword() throws ScanException { { List<Token> tl = new TokenStream("%d(A)", new AlmostAsIsEscapeUtil()).tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(Token.PERCENT_TOKEN); witness.add(new Token(Token.COMPOSI...
@Deprecated public String withNamespace(String resource) { return NamespaceUtil.wrapNamespace(this.getNamespace(), resource); }
@Test public void testWithNamespace() { Set<String> resources = clientConfig.withNamespace(Collections.singleton(resource)); assertTrue(resources.contains("lmq%resource")); }
protected NodeLabelsProvider createNodeLabelsProvider(Configuration conf) throws IOException { NodeLabelsProvider provider = null; String providerString = conf.get(YarnConfiguration.NM_NODE_LABELS_PROVIDER_CONFIG, null); if (providerString == null || providerString.trim().length() == 0) { ...
@Test public void testCreationOfNodeLabelsProviderService() throws InterruptedException { try { NodeManager nodeManager = new NodeManager(); Configuration conf = new Configuration(); NodeLabelsProvider labelsProviderService = nodeManager.createNodeLabelsProvider(conf); Asse...
@Override public BulkOperationResponse executeBulkOperation(final BulkOperationRequest bulkOperationRequest, final C userContext, final AuditParams params) { if (bulkOperationRequest.entityIds() == null || bulkOperationRequest.entityIds().isEmpty()) { throw new BadRequestException(NO_ENTITY_IDS_...
@Test void throwsBadRequestExceptionOnNullEntityIdsList() { assertThrows(BadRequestException.class, () -> toTest.executeBulkOperation(new BulkOperationRequest(null), context, params), NO_ENTITY_IDS_ERROR); }
@Override public ConnectionProperties parse(final String url, final String username, final String catalog) { JdbcUrl jdbcUrl = new StandardJdbcUrlParser().parse(url); return new StandardConnectionProperties(jdbcUrl.getHostname(), jdbcUrl.getPort(DEFAULT_PORT), jdbcUrl.getDatabase(), null, jdbcUrl.ge...
@Test void assertNewConstructorFailure() { assertThrows(UnrecognizedDatabaseURLException.class, () -> parser.parse("jdbc:opengauss:xxxxxxxx", null, null)); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { this.trash(files, prompt, callback); for(Path f : files.keySet()) { fileid.cache(f, null); } }
@Test public void testDeleteFileInTrash() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path file = new EueTouchFeature(session, fileid).touch(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus(...
@Override public void doRun() { if (versionOverride.isPresent()) { LOG.debug("Elasticsearch version is set manually. Not running check."); return; } final Optional<SearchVersion> probedVersion = this.versionProbe.probe(this.elasticsearchHosts); probedVersion...
@Test void doesNotRunIfVersionOverrideIsSet() { createPeriodical(SearchVersion.elasticsearch(8, 0, 0), SearchVersion.elasticsearch(7, 0, 0)).doRun(); verifyNoInteractions(notificationService); }
public static String getRemoteAddr(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String proxyHeader = request.getHeader("X-Forwarded-For"); if (proxyHeader != null && ProxyServers.isProxyServer(remoteAddr)) { final String clientAddr = proxyHeader.split(",")[0].trim(); ...
@Test public void testRemoteAddrWithUntrustedProxy() { assertEquals(proxyAddr, getRemoteAddr(clientAddr, proxyAddr, false)); }
@Override public void dispatch(DispatchRequest request) { if (!this.brokerConfig.isEnableCalcFilterBitMap()) { return; } try { Collection<ConsumerFilterData> filterDatas = consumerFilterManager.get(request.getTopic()); if (filterDatas == null || filterD...
@Test public void testDispatch() { BrokerConfig brokerConfig = new BrokerConfig(); brokerConfig.setEnableCalcFilterBitMap(true); ConsumerFilterManager filterManager = ConsumerFilterManagerTest.gen(10, 10); CommitLogDispatcherCalcBitMap calcBitMap = new CommitLogDispatcherCalcBitMap...
public static SSLFactory createSSLFactoryAndEnableAutoRenewalWhenUsingFileStores(TlsConfig tlsConfig) { return createSSLFactoryAndEnableAutoRenewalWhenUsingFileStores(tlsConfig, () -> false); }
@Test public void createSSLFactoryAndEnableAutoRenewalWhenUsingFileStoresWithPinotSecureMode() throws IOException, URISyntaxException, InterruptedException { TlsConfig tlsConfig = createTlsConfig(); SSLFactory sslFactory = RenewableTlsUtils.createSSLFactoryAndEnableAutoRenewalWhenUsingFileStores...
public String convert(ILoggingEvent le) { long timestamp = le.getTimeStamp(); return cachingDateFormatter.format(timestamp); }
@Test public void convertsDateAsIso8601WhenInvalidPatternSpecified() { assertEquals(_isoDateString, convert(_timestamp, "foo")); }
@Override public Collection<ThreadPoolPluginSupport> getAllManagedThreadPoolPluginSupports() { return managedThreadPoolPluginSupports.values(); }
@Test public void testGetAllManagedThreadPoolPluginSupports() { GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager(); manager.registerThreadPoolPluginSupport(new TestSupport("1")); manager.registerThreadPoolPluginSupport(new TestSupport("2")); Assert.ass...
@Override @CacheEvict(value = RedisKeyConstants.ROLE, key = "#id") public void updateRoleDataScope(Long id, Integer dataScope, Set<Long> dataScopeDeptIds) { // 校验是否可以更新 validateRoleForUpdate(id); // 更新数据范围 RoleDO updateObject = new RoleDO(); updateObject.setId(id); ...
@Test public void testUpdateRoleDataScope() { // mock 数据 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType())); roleMapper.insert(roleDO); // 准备参数 Long id = roleDO.getId(); Integer dataScope = randomEle(DataScopeEnum.values()).getScop...
public String getUserAgent() { return userAgent; }
@Test public void testGetUserAgent() { shenyuRequestLog.setUserAgent("test"); Assertions.assertEquals(shenyuRequestLog.getUserAgent(), "test"); }
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext, final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon...
@Test void assertNewInstanceForStandard() { SQLStatement sqlStatement = mock(SQLStatement.class); when(sqlStatementContext.getSqlStatement()).thenReturn(sqlStatement); tableNames.add(""); when(shardingRule.getShardingLogicTableNames(((TableAvailable) sqlStatementContext).getTablesCon...
@Override public long getPeriodMillis() { return periodMillis; }
@Test public void testGetPeriodMillis() { assertEquals(SECONDS.toMillis(60), plugin.getPeriodMillis()); }
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldExtractAsAliasedDataSources() { // Given: final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1 AS t;"); // When: final Query result = (Query) builder.buildStatement(stmt); // Then: assertThat(result.getFrom(), is(new AliasedRelation(TEST1, SourceName.of...
public static Map<String, AdvertisedListener> validateAndAnalysisAdvertisedListener(ServiceConfiguration config) { if (StringUtils.isBlank(config.getAdvertisedListeners())) { return Collections.emptyMap(); } Optional<String> firstListenerName = Optional.empty(); Map<String, L...
@Test(expectedExceptions = IllegalArgumentException.class) public void testListenerDuplicate_3() { ServiceConfiguration config = new ServiceConfiguration(); config.setAdvertisedListeners(" internal:pulsar+ssl://127.0.0.1:6661," + " internal:pulsar+ssl://192.168.1.11:6661"); config.setInterna...
static int bucketMinUs(int bucket) { return bucket == 0 ? 0 : 1 << bucket; }
@Test public void bucketMinUs() { assertEquals(0, LatencyDistribution.bucketMinUs(0)); assertEquals(2, LatencyDistribution.bucketMinUs(1)); assertEquals(4, LatencyDistribution.bucketMinUs(2)); assertEquals(8, LatencyDistribution.bucketMinUs(3)); assertEquals(16, LatencyDistri...
@Override public Set<OAuth2RefreshTokenEntity> getRefreshTokensByUserName(String name) { TypedQuery<OAuth2RefreshTokenEntity> query = manager.createNamedQuery(OAuth2RefreshTokenEntity.QUERY_BY_NAME, OAuth2RefreshTokenEntity.class); query.setParameter(OAuth2RefreshTokenEntity.PARAM_NAME, name); List<OAuth2R...
@Test public void testGetRefreshTokensByUserName() { Set<OAuth2RefreshTokenEntity> tokens = repository.getRefreshTokensByUserName("user2"); assertEquals(3, tokens.size()); assertEquals("user2", tokens.iterator().next().getAuthenticationHolder().getUserAuth().getName()); }
public static AllMatches allMatches(String regex) { return allMatches(Pattern.compile(regex)); }
@Test @Category(NeedsRunner.class) public void testAllMatches() { PCollection<List<String>> output = p.apply(Create.of("a x", "x x", "y y", "z z")).apply(Regex.allMatches("([xyz]) ([xyz])")); PAssert.that(output) .containsInAnyOrder( Arrays.asList("x x", "x", "x"), ...
public static <T extends Enum<T>> Validator enumValues(final Class<T> enumClass) { final String[] enumValues = EnumSet.allOf(enumClass) .stream() .map(Object::toString) .toArray(String[]::new); final String[] validValues = Arrays.copyOf(enumValues, enumValues.length + 1); validValue...
@Test public void shouldNotThrowIfAValidEnumValue() { // Given: final Validator validator = ConfigValidators.enumValues(TestEnum.class); // When: validator.ensureValid("propName", TestEnum.FOO.toString()); // Then: did not throw }
public static JibContainerBuilder create( String baseImageReference, Set<Platform> platforms, CommonCliOptions commonCliOptions, ConsoleLogger logger) throws InvalidImageReferenceException, FileNotFoundException { if (baseImageReference.startsWith(DOCKER_DAEMON_IMAGE_PREFIX)) { r...
@Test public void testCreate_registry() throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { JibContainerBuilder containerBuilder = ContainerBuilders.create( "registry://registry-image-ref", Collections.emptySet(), mockCommonCliOpt...
@Override public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() { checkState(authAppInstallationToken != null, "An auth app token is required in case repository permissions checking is necessary."); String[] orgaAndRepoTokenified = devOpsProjectCreationContext.fullName().split("/"); String org...
@Test void isScanAllowedUsingPermissionsFromDevopsPlatform_whenAccessViaTeam_returnsTrue() { GsonRepositoryTeam team1 = mockGithubTeam("team1", 1, "role1", "read", "another_perm"); GsonRepositoryTeam team2 = mockGithubTeam("team2", 2, "role2", "another_perm", UserRole.SCAN); mockTeamsFromApi(team1, team2)...
@Override public RestLiResponseData<BatchGetResponseEnvelope> buildRestLiResponseData(Request request, RoutingResult routingResult, Object result, Map<Strin...
@Test(dataProvider = "exceptionTestData") public void testBuilderExceptions(Object results, String expectedErrorMessage) { // Protocol version doesn't matter here ServerResourceContext mockContext = getMockResourceContext(null, Collections.emptyMap(), null, null, null); ResourceMethodDescriptor ...
public static HintValueContext extractHint(final String sql) { if (!containsSQLHint(sql)) { return new HintValueContext(); } HintValueContext result = new HintValueContext(); int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql); String hintKeyValueText = sql.su...
@Test void assertSQLHintShardingTableValueWithStringHintValue() { HintValueContext actual = SQLHintUtils.extractHint("/* SHARDINGSPHERE_HINT: t_order.SHARDING_TABLE_VALUE=a */"); assertThat(actual.getHintShardingTableValue("t_order"), is(Collections.singletonList("a"))); }
@Override public final boolean next() { if (memoryResultSetRows.hasNext()) { currentResultSetRow = memoryResultSetRows.next(); return true; } return false; }
@Test void assertNext() { assertTrue(memoryMergedResult.next()); assertFalse(memoryMergedResult.next()); }
@Override public UsersSearchRestResponse toUsersForResponse(List<UserInformation> userInformations, PaginationInformation paginationInformation) { List<UserRestResponse> usersForResponse = toUsersForResponse(userInformations); PageRestResponse pageRestResponse = new PageRestResponse(paginationInformation.page...
@Test public void toUsersForResponse_whenAnonymous_returnsOnlyNameAndLogin() { PaginationInformation paging = forPageIndex(1).withPageSize(2).andTotal(3); UserInformation userInformation1 = mockSearchResult(1, true); UserInformation userInformation2 = mockSearchResult(2, false); UsersSearchRestRespo...
@Override @Nullable public Object convert(@Nullable String value) { if (isNullOrEmpty(value)) { return null; } LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone); final DateTimeFormatter form...
@Test public void testNullInput() throws Exception { final DateConverter converter = new DateConverter(config("yyyy-MM-dd'T'HH:mm:ss.SSSZ", null, null)); assertThat((DateTime) converter.convert(null)).isNull(); }
public static String getSrcUserName(HttpServletRequest request) { IdentityContext identityContext = RequestContextHolder.getContext().getAuthContext().getIdentityContext(); String result = StringUtils.EMPTY; if (null != identityContext) { result = (String) identityContext.getParamete...
@Test void testGetSrcUserNameFromRequest() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getParameter(eq(Constants.USERNAME))).thenReturn("parameterName"); assertEquals("parameterName", RequestUtil.getSrcUserName(request)); }
@Override public Map<String, Object> getUserProperties() { if (principal instanceof KsqlPrincipal) { return ((KsqlPrincipal) principal).getUserProperties(); } else { return Collections.emptyMap(); } }
@Test public void shouldReturnUserProperties() { assertThat(wrappedKsqlPrincipal.getUserProperties(), is(USER_PROPERTIES)); assertThat(wrappedOtherPrincipal.getUserProperties(), is(Collections.emptyMap())); }
@Override public boolean hasSameDbVendor() { Optional<String> registeredDbVendor = metadataIndex.getDbVendor(); return registeredDbVendor.isPresent() && registeredDbVendor.get().equals(getDbVendor()); }
@Test public void hasSameDbVendor_is_false_if_value_is_absent_from_es() { prepareDb("mssql"); assertThat(underTest.hasSameDbVendor()).isFalse(); }
public StatsOutputStream writePair(String name, boolean value) { checkSeparator(); write('"').writeEncoded(name).write("\":").write(value); return this; }
@Test public void testPairs() { stream.writePair("my-count", 1); assertEquals(str(), "\"my-count\":1"); stream.writePair("my-rate", 0.0); assertEquals(str(), "\"my-rate\":0.0"); stream.writePair("my-flag", true); assertEquals(str(), "\"my-flag\":true"); str...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldCastNullBigInt() { // When: final BigDecimal decimal = DecimalUtil.cast((Long)null, 2, 1); // Then: assertThat(decimal, is(nullValue())); }
@VisibleForTesting static Comparator<ActualProperties> streamingExecutionPreference(PreferredProperties preferred) { // Calculating the matches can be a bit expensive, so cache the results between comparisons LoadingCache<List<LocalProperty<VariableReferenceExpression>>, List<Optional<LocalPrope...
@Test public void testPickLayoutUnpartitionedPreference() { Comparator<ActualProperties> preference = streamingExecutionPreference(PreferredProperties.undistributed()); List<ActualProperties> input = ImmutableList.<ActualProperties>builder() .add(builder() ...
@Override public void add(long hash) { convertToDenseIfNeeded(); boolean changed = encoder.add(hash); if (changed) { cachedEstimate = null; } }
@Test public void add() { hyperLogLog.add(1000L); assertEquals(1L, hyperLogLog.estimate()); }
public Optional<Details> sync( @NotNull StepInstance instance, @NotNull WorkflowSummary workflowSummary, @NotNull StepRuntimeSummary stepSummary) { try { switch (stepSummary.getDbOperation()) { case INSERT: case UPSERT: instanceDao.insertOrUpsertStepInstance( ...
@Test public void testInvalidDbOperation() { StepRuntimeSummary stepRuntimeSummary = StepRuntimeSummary.builder() .stepId("test-summary") .stepAttemptId(2) .stepInstanceId(1) .dbOperation(DbOperation.DELETE) .build(); Optional<Details> detail...
public String name() { return name; }
@Test void testName() { final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.INTELLECT, 2); assertNull(prototype.name()); final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertNull(stupid.name()); final var...
static void setStaticGetter(final CompilationDTO<ClusteringModel> compilationDTO, final ClassOrInterfaceDeclaration modelTemplate) { KiePMMLModelFactoryUtils.initStaticGetter(compilationDTO, modelTemplate); final BlockStmt body = getMethodDeclarationBlockStmt(modelTemplat...
@Test void setStaticGetter() throws IOException { final ClassOrInterfaceDeclaration modelTemplate = MODEL_TEMPLATE.clone(); final CommonCompilationDTO<ClusteringModel> compilationDTO = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME, ...
@Override public String toString() { String bounds = printExtendsClause() ? " extends " + joinTypeNames(upperBounds) : ""; return getClass().getSimpleName() + '{' + getName() + bounds + '}'; }
@Test public void toString_upper_bounded_by_multiple_bounds() { @SuppressWarnings("unused") class BoundedByMultipleBounds<NAME extends String & Serializable> { } JavaTypeVariable<JavaClass> typeVariable = new ClassFileImporter().importClass(BoundedByMultipleBounds.class).getTypePara...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldThrowInCreateStreamOrReplaceSource() { // Given: final CreateStream ddlStatement = new CreateStream(SOME_NAME, STREAM_ELEMENTS, true, false, withProperties, true); // When: final Exception e = assertThrows( KsqlException.class, () -> createSourceFactory ...
public void writeNumIncreasing(long value) { // Values are encoded with a single byte length prefix, followed // by the actual value in big-endian format with leading 0 bytes // dropped. byte[] bufer = new byte[9]; // 8 bytes for value plus one byte for length int len = 0; while (value != 0) { ...
@Test public void testWriteNumIncreasing() { OrderedCode orderedCode = new OrderedCode(); orderedCode.writeNumIncreasing(0); orderedCode.writeNumIncreasing(1); orderedCode.writeNumIncreasing(Long.MIN_VALUE); orderedCode.writeNumIncreasing(Long.MAX_VALUE); assertEquals(0, orderedCode.readNumInc...
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void timeZone_ifZoneFromQueryIsUnknown_fallbacksToClockZone() { SearchRequest request = new SearchRequest().setTimeZone("Poitou-Charentes"); when(clock.getZone()).thenReturn(ZoneId.systemDefault()); IssueQuery issueQuery = underTest.create(request); assertThat(issueQuery.timeZone()).isEq...
@Override public void broadcastOnIssueChange(List<DefaultIssue> issues, Collection<QGChangeEvent> changeEvents, boolean fromAlm) { if (listeners.isEmpty() || issues.isEmpty() || changeEvents.isEmpty()) { return; } try { broadcastChangeEventsToBranches(issues, changeEvents, fromAlm); } cat...
@Test public void broadcastOnIssueChange_has_no_effect_when_issues_are_empty() { underTest.broadcastOnIssueChange(emptyList(), singletonList(component1QGChangeEvent), false); verifyNoInteractions(listener1, listener2, listener3); }
@Override public boolean isProvisioningEnabled() { return isEnabled() && configuration.getBoolean(GITLAB_AUTH_PROVISIONING_ENABLED).orElse(false); }
@Test public void isProvisioningEnabled_ifProvisioningEnabledAndGithubAuthEnabled_returnsTrue() { enableGitlabAuthentication(); settings.setProperty(GITLAB_AUTH_PROVISIONING_ENABLED, true); assertThat(config.isProvisioningEnabled()).isTrue(); }
public RemotingCommand cleanExpiredConsumeQueue() { LOGGER.info("AdminBrokerProcessor#cleanExpiredConsumeQueue: start."); final RemotingCommand response = RemotingCommand.createResponseCommand(null); try { brokerController.getMessageStore().cleanExpiredConsumerQueue(); } catc...
@Test public void testCleanExpiredConsumeQueue() throws RemotingCommandException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_EXPIRED_CONSUMEQUEUE, null); RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request); assertThat...
public File createFile(String fileName) throws IOException { File file = new File(tempFolder(), fileName); file.getParentFile().mkdirs(); file.createNewFile(); createdFiles.add(file); return file; }
@Test public void shouldCreateFilesInTempDirectory() throws IOException { File file = files.createFile("foo"); File parentFile = file.getParentFile(); assertThat(parentFile.getName(), is("cruise")); assertThat(parentFile.getParentFile(), is(tmpDir())); }
public ClientTelemetrySender telemetrySender() { return clientTelemetrySender; }
@Test public void testTelemetrySenderTimeToNextUpdate() { ClientTelemetryReporter.DefaultClientTelemetrySender telemetrySender = (ClientTelemetryReporter.DefaultClientTelemetrySender) clientTelemetryReporter.telemetrySender(); assertEquals(ClientTelemetryState.SUBSCRIPTION_NEEDED, telemetrySender.s...
@SuppressWarnings("unchecked") @Udf public <T> List<T> union( @UdfParameter(description = "First array of values") final List<T> left, @UdfParameter(description = "Second array of values") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> combined ...
@Test public void shouldUnionArraysContainingNulls() { final List<String> input1 = Arrays.asList(null, "bar"); final List<String> input2 = Arrays.asList("foo"); final List<String> result = udf.union(input1, input2); assertThat(result, contains(null, "bar", "foo")); }
@PostMapping("/import") @RequiresPermissions("system:manager:importConfig") public ShenyuAdminResult importConfigs(final MultipartFile file) { if (Objects.isNull(file)) { return ShenyuAdminResult.error(ShenyuResultMessage.PARAMETER_ERROR); } try { ShenyuAdminResul...
@Test public void testImportConfigs() throws Exception { // mock import data List<ZipUtil.ZipItem> zipItemList = Lists.newArrayList(); when(this.configsService.configsImport(any())).thenReturn( ShenyuAdminResult.success(ShenyuResultMessage.SUCCESS)); // mock file ...
public ApplicationStatus appendNewState(ApplicationState state) { return new ApplicationStatus( state, createUpdatedHistoryWithNewState(state), previousAttemptSummary, currentAttemptSummary); }
@Test void testAppendNewState() { ApplicationStatus applicationStatus = new ApplicationStatus(); ApplicationState newState = new ApplicationState(ApplicationStateSummary.RunningHealthy, "foo"); ApplicationStatus newStatus = applicationStatus.appendNewState(newState); assertEquals(2, newStatus.getState...
boolean canFilterPlayer(String playerName) { boolean isMessageFromSelf = playerName.equals(client.getLocalPlayer().getName()); return !isMessageFromSelf && (config.filterFriends() || !client.isFriended(playerName, false)) && (config.filterFriendsChat() || !isFriendsChatMember(playerName)) && (config.filte...
@Test public void testMessageFromFriendIsNotFiltered() { when(client.isFriended("Iron Mammal", false)).thenReturn(true); when(chatFilterConfig.filterFriends()).thenReturn(false); assertFalse(chatFilterPlugin.canFilterPlayer("Iron Mammal")); }
@Override public Properties info(RedisClusterNode node) { Map<String, String> info = execute(node, RedisCommands.INFO_ALL); Properties result = new Properties(); for (Entry<String, String> entry : info.entrySet()) { result.setProperty(entry.getKey(), entry.getValue()); } ...
@Test public void testInfo() { RedisClusterNode master = getFirstMaster(); Properties info = connection.info(master); assertThat(info.size()).isGreaterThan(10); }