focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Deserializer deserializer(String topic, Target type) { return (headers, data) -> { var schemaId = extractSchemaIdFromMsg(data); SchemaType format = getMessageFormatBySchemaId(schemaId); MessageFormatter formatter = schemaRegistryFormatters.get(format); return new Deseriali...
@Test void deserializeReturnsJsonAvroMsgJsonRepresentation() throws RestClientException, IOException { AvroSchema schema = new AvroSchema( "{" + " \"type\": \"record\"," + " \"name\": \"TestAvroRecord1\"," + " \"fields\": [" + " {" + " ...
@GET @Path(GET_INFO) @ApiOperation(value = "Get general Alluxio Master service information", response = alluxio.wire.AlluxioMasterInfo.class) public Response getInfo(@QueryParam(QUERY_RAW_CONFIGURATION) final Boolean rawConfiguration) { // TODO(jiri): Add a mechanism for retrieving only a subset of the ...
@Test public void getMasterInfo() { // Mock for rpc address when(mMasterProcess.getRpcAddress()).thenReturn(new InetSocketAddress("localhost", 8080)); // Mock for metrics final int FILES_PINNED_TEST_VALUE = 100; String filesPinnedProperty = MetricKey.MASTER_FILES_PINNED.getName(); Gauge<Intege...
public String getDomainObjectName() { if (stringHasValue(domainObjectName)) { return domainObjectName; } String finalDomainObjectName; if (stringHasValue(runtimeTableName)) { finalDomainObjectName = JavaBeansUtil.getCamelCaseString(runtimeTableName, true); ...
@Test void testRenamingRuleNoUnderscore() { DomainObjectRenamingRule renamingRule = new DomainObjectRenamingRule(); renamingRule.setSearchString("^Sys"); renamingRule.setReplaceString(""); FullyQualifiedTable fqt = new FullyQualifiedTable(null, "myschema", "sysmytable", null, null, f...
public static Optional<CheckpointStorage> fromConfig( ReadableConfig config, ClassLoader classLoader, @Nullable Logger logger) throws IllegalStateException, DynamicCodeLoadingException { Preconditions.checkNotNull(config, "config"); Preconditions.checkNotNull(classLoader, "class...
@Test void testLoadFileSystemCheckpointStorage() throws Exception { final String checkpointDir = new Path(TempDirUtils.newFolder(tmp).toURI()).toString(); final String savepointDir = new Path(TempDirUtils.newFolder(tmp).toURI()).toString(); final Path expectedCheckpointsPath = new Path(check...
@Override public Coder<SqsCheckpointMark> getCheckpointMarkCoder() { return SerializableCoder.of(SqsCheckpointMark.class); }
@Test public void testCheckpointCoderIsSane() { final AmazonSQS client = embeddedSqsRestServer.getClient(); final String queueUrl = embeddedSqsRestServer.getQueueUrl(); client.sendMessage(queueUrl, DATA); SqsUnboundedSource source = new SqsUnboundedSource( SqsIO.read().withQueueUrl...
public static Exception toException(int code, String msg) throws Exception { if (code == Response.Status.NOT_FOUND.getStatusCode()) { throw new NotFoundException(msg); } else if (code == Response.Status.NOT_IMPLEMENTED.getStatusCode()) { throw new ClassNotFoundException(msg); ...
@Test public void testToExceptionSerializationException() { assertThrows(InvalidRequestException.class, () -> RestExceptionMapper.toException(Response.Status.BAD_REQUEST.getStatusCode(), "Bad Request")); }
public static NamenodeRole convert(NamenodeRoleProto role) { switch (role) { case NAMENODE: return NamenodeRole.NAMENODE; case BACKUP: return NamenodeRole.BACKUP; case CHECKPOINT: return NamenodeRole.CHECKPOINT; } return null; }
@Test public void testConvertBlockRecoveryCommand() { DatanodeInfo di1 = DFSTestUtil.getLocalDatanodeInfo(); DatanodeInfo di2 = DFSTestUtil.getLocalDatanodeInfo(); DatanodeInfo[] dnInfo = new DatanodeInfo[] { di1, di2 }; List<RecoveringBlock> blks = ImmutableList.of( new RecoveringBlock(getExte...
@NonNull public Client authenticate(@NonNull Request request) { // https://datatracker.ietf.org/doc/html/rfc7521#section-4.2 try { if (!CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT.equals(request.clientAssertionType())) { throw new AuthenticationException( "unsupported client_assertion_ty...
@Test void authenticate_expired() throws JOSEException { var key = generateKey(); var jwkSource = new StaticJwkSource<>(key); var inThePast = Date.from(Instant.now().minusSeconds(60)); var claims = new JWTClaimsSet.Builder() .audience(RP_ISSUER.toString()) .subject("...
@Override public GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request) throws YarnException, IOException { if (request == null || request.getApplicationId() == null) { routerMetrics.incrAppsFailedRetrieved(); String errMsg = "Missing getApplicationReport reques...
@Test public void testGetApplicationNotExists() throws Exception { LOG.info("Test ApplicationClientProtocol: Get Application Report - Not Exists."); ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1); GetApplicationReportRequest requestGet = GetApplicationReportRequest.n...
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type =...
@Test public void applyGeneratesBigDecimalOverridingDouble() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "number"); //this shows that isUseBigDecimals over...
public void print(PrintStream out, String prefix) { print(out, prefix, data, data.length); }
@Test public void testPrintNonPrintable() { byte[] buf = new byte[12]; Arrays.fill(buf, (byte) 0x04); ZData data = new ZData(buf); data.print(System.out, "ZData: "); }
@VisibleForTesting public File getStorageLocation(@Nullable JobID jobId, BlobKey key) throws IOException { return BlobUtils.getStorageLocation(storageDir.deref(), jobId, key); }
@Test void transientBlobCacheTimesOutRecoveredBlobs(@TempDir Path storageDirectory) throws Exception { final JobID jobId = new JobID(); final TransientBlobKey transientBlobKey = TestingBlobUtils.writeTransientBlob( storageDirectory, jobId, new byte[] {1, 2, 3,...
public String mapSrv(String responsibleTag) { final List<String> servers = healthyList; if (CollectionUtils.isEmpty(servers) || !switchDomain.isDistroEnabled()) { return EnvUtil.getLocalAddress(); } try { int index = distroHash(responsibleTag) % ...
@Test void testMapSrv() { String server = distroMapper.mapSrv(serviceName); assertEquals(server, ip4); }
public static String toStringAddress(SocketAddress address) { if (address == null) { return StringUtils.EMPTY; } return toStringAddress((InetSocketAddress) address); }
@Test public void testToStringAddress() { try { String stringAddress = NetUtil.toStringAddress(InetSocketAddress.createUnresolved("127.0.0.1", 9828)); } catch (Exception e) { assertThat(e).isInstanceOf(NullPointerException.class); } }
public static <X extends Throwable> void isTrue(boolean expression, Supplier<? extends X> supplier) throws X { if (false == expression) { throw supplier.get(); } }
@Test public void isTrueTest() { Assertions.assertThrows(IllegalArgumentException.class, () -> { int i = 0; //noinspection ConstantConditions cn.hutool.core.lang.Assert.isTrue(i > 0, IllegalArgumentException::new); }); }
@Override public String key() { return PropertyType.STRING.name(); }
@Test public void key() { assertThat(validation.key()).isEqualTo("STRING"); }
@NonNull @Override public ConnectionFileName toPvfsFileName( @NonNull FileName providerFileName, @NonNull T details ) throws KettleException { // Determine the part of provider file name following the connection "root". // Use the transformer to generate the connection root provider uri. // Both uri...
@Test( expected = IllegalArgumentException.class ) public void testToPvfsFileNameThrowsIfProviderUriIsNotDescendantOfConnectionRootUri() throws Exception { mockDetailsWithDomain( details1, "my-domain:8080" ); mockDetailsWithRootPath( details1, "my/root/path" ); // Note the `another-domain` which is diff...
@Override public String toString() { int numColumns = getColumnCount(); TextTable table = new TextTable(); String[] columnNames = new String[numColumns]; String[] columnDataTypes = new String[numColumns]; for (int c = 0; c < numColumns; c++) { columnNames[c] = _columnNamesArray.get(c).asText...
@Test public void testToString() { // Run the test final String result = _resultTableResultSetUnderTest.toString(); // Verify the results assertNotEquals("", result); }
public JerseyClientBuilder using(JerseyClientConfiguration configuration) { this.configuration = configuration; apacheHttpClientBuilder.using(configuration); return this; }
@Test void usesACustomHostnameVerifier() { final HostnameVerifier customHostnameVerifier = new NoopHostnameVerifier(); builder.using(customHostnameVerifier); verify(apacheHttpClientBuilder).using(customHostnameVerifier); }
static String convertEnvVars(String input){ // check for any non-alphanumeric chars and convert to underscore // convert to upper case if (input == null) { return null; } return input.replaceAll("[^A-Za-z0-9]", "_").toUpperCase(); }
@Test public void testConvertEnvVarsUsingEmptyString() { String testInput3 = ConfigInjection.convertEnvVars(""); Assert.assertEquals("", testInput3); }
public static int findThread(String expectedThread) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logThread = logList.get(i).getLogThread(); if (logThread.contains(expectedThread)) { count++; ...
@Test void testFindThread() { Log log = mock(Log.class); DubboAppender.logList.add(log); when(log.getLogThread()).thenReturn("thread-1"); assertThat(LogUtil.findThread("thread-1"), equalTo(1)); }
@Override public void keyPressed(KeyEvent e) { if (!plugin.chatboxFocused()) { return; } if (!plugin.isTyping()) { int mappedKeyCode = KeyEvent.VK_UNDEFINED; if (config.cameraRemap()) { if (config.up().matches(e)) { mappedKeyCode = KeyEvent.VK_UP; } else if (config.down()....
@Test public void testControlRemap() { when(keyRemappingConfig.control()).thenReturn(new ModifierlessKeybind(KeyEvent.VK_NUMPAD1, 0)); when(keyRemappingPlugin.chatboxFocused()).thenReturn(true); KeyEvent event = mock(KeyEvent.class); when(event.getExtendedKeyCode()).thenReturn(KeyEvent.VK_NUMPAD1); // for ke...
public static String getNacosHome() { if (StringUtils.isBlank(nacosHomePath)) { String nacosHome = System.getProperty(NACOS_HOME_KEY); if (StringUtils.isBlank(nacosHome)) { nacosHome = Paths.get(System.getProperty(NACOS_HOME_PROPERTY), NACOS_HOME_ADDITIONAL_FILEPATH) ...
@Test void test() { String nacosHome = EnvUtils.getNacosHome(); assertEquals(System.getProperty("user.home") + File.separator + "nacos", nacosHome); System.setProperty("nacos.home", "test"); String testHome = EnvUtils.getNacosHome(); assertEquals("test", testHome); ...
@Override public RecordCursor cursor() { return new JdbcRecordCursor(jdbcClient, session, split, columnHandles); }
@Test public void testCursorSimple() { RecordSet recordSet = new JdbcRecordSet(jdbcClient, session, split, ImmutableList.of( columnHandles.get("text"), columnHandles.get("text_short"), columnHandles.get("value"))); try (RecordCursor cursor = recor...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(containerService.isContainer(file)) { return PathAttributes.EMPTY; } return th...
@Test public void testReadAtSignInKey() throws Exception { final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(session)).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); ...
@Udf(description = "Converts a string representation of a time in the given format" + " into the TIME value.") public Time parseTime( @UdfParameter( description = "The string representation of a time.") final String formattedTime, @UdfParameter( description = "The format pattern ...
@Test public void shouldSupportEmbeddedChars() { // When: final Time result = udf.parseTime("000105.000Fred", "HHmmss.SSS'Fred'"); // Then: assertThat(result.getTime(), is(65000L)); }
@VisibleForTesting ClientConfiguration createBkClientConfiguration(MetadataStoreExtended store, ServiceConfiguration conf) { ClientConfiguration bkConf = new ClientConfiguration(); if (conf.getBookkeeperClientAuthenticationPlugin() != null && conf.getBookkeeperClientAuthenticationPlu...
@Test public void testOpportunisticStripingConfiguration() { BookKeeperClientFactoryImpl factory = new BookKeeperClientFactoryImpl(); ServiceConfiguration conf = new ServiceConfiguration(); // default value assertFalse(factory.createBkClientConfiguration(mock(MetadataStoreExtended.cl...
@Override public String decrypt(final String key, final byte[] encryptData) throws Exception { byte[] decoded = Base64.getDecoder().decode(key); PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded)); Cipher cipher = Cipher.getInstance(RSA); ...
@Test public void testDecrypt() throws Exception { assertThat(cryptorStrategy.decrypt(decKey, encryptedData), is(decryptedData)); }
public static MilliPct ofPercent(float value) { return new MilliPct(Float.valueOf(value * 1000f).intValue()); }
@Test public void testOfPercent() { assertEquals(63563, MilliPct.ofPercent(63.563f).intValue()); assertEquals(-63563, MilliPct.ofPercent(-63.563f).intValue()); }
@Override public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) { ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new); String columnName = shardingValue.getColumnName(); ...
@Test void assertDoShardingWithLargeValues() { List<String> availableTargetNames = Lists.newArrayList("t_order_0", "t_order_1", "t_order_2", "t_order_3"); assertThat(inlineShardingAlgorithm.doSharding(availableTargetNames, new PreciseShardingValue<>("t_order", "order_id", DATA_NODE_I...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldDeserializeDecimalsWithoutStrippingTrailingZeros() { // Given: final KsqlJsonDeserializer<BigDecimal> deserializer = givenDeserializerForSchema(DecimalUtil.builder(3, 1).build(), BigDecimal.class); final byte[] bytes = addMagic("10.0".getBytes(UTF_8)); // When: f...
@Override public StatusOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class); if(log.isDebugEnabl...
@Test public void testWrite() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volum...
@Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { switch (request.getCode()) { case RequestCode.GET_CONSUMER_LIST_BY_GROUP: return this.getConsumerListByGroup(ctx, request); ca...
@Test public void testUpdateConsumerOffset_GroupNotExist() throws Exception { RemotingCommand request = buildUpdateConsumerOffsetRequest("NotExistGroup", topic, 0, 0); RemotingCommand response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull()...
Converter<E> compile() { head = tail = null; for (Node n = top; n != null; n = n.next) { switch (n.type) { case Node.LITERAL: addToList(new LiteralConverter<E>((String) n.getValue())); break; case Node.COMPOSITE_KEYWORD: ...
@Test public void testComposite() throws Exception { // { // Parser<Object> p = new Parser<Object>("%(ABC)"); // p.setContext(context); // Node t = p.parse(); // Converter<Object> head = p.compile(t, converterMap); // String result = write(head, new Object()); ...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testSlaughterRegenerate() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", REGENERATE_BRACELET_OF_SLAUGHTER, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACE...
public boolean isMulticast() { return isIp4() ? IPV4_MULTICAST_PREFIX.contains(this.getIp4Prefix()) : IPV6_MULTICAST_PREFIX.contains(this.getIp6Prefix()); }
@Test public void testIsMulticast() { IpPrefix v4Unicast = IpPrefix.valueOf("10.0.0.1/16"); IpPrefix v4Multicast = IpPrefix.valueOf("224.0.0.1/4"); IpPrefix v4Overlap = IpPrefix.valueOf("192.0.0.0/2"); IpPrefix v6Unicast = IpPrefix.valueOf("1000::1/8"); IpPrefix v6Multicast =...
@InvokeOnHeader(Web3jConstants.ETH_SYNCING) void ethSyncing(Message message) throws IOException { Request<?, EthSyncing> request = web3j.ethSyncing(); setRequestId(message, request); EthSyncing response = request.send(); boolean hasError = checkForError(message, response); if...
@Test public void ethSyncingTest() throws Exception { EthSyncing response = Mockito.mock(EthSyncing.class); Mockito.when(mockWeb3j.ethSyncing()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.isSyncing()).thenReturn(Boolean.TRUE); ...
public Domain intersect(Domain other) { checkCompatibility(other); return new Domain(values.intersect(other.getValues()), this.isNullAllowed() && other.isNullAllowed()); }
@Test public void testIntersect() { assertEquals( Domain.all(BIGINT).intersect(Domain.all(BIGINT)), Domain.all(BIGINT)); assertEquals( Domain.none(BIGINT).intersect(Domain.none(BIGINT)), Domain.none(BIGINT)); assertEquals(...
@Nonnull public static <C> SourceBuilder<C>.Batch<Void> batch( @Nonnull String name, @Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn ) { return new SourceBuilder<C>(name, createFn).new Batch<>(); }
@Test public void stream_socketSource_distributed() throws IOException { // Given try (ServerSocket serverSocket = new ServerSocket(0)) { startServer(serverSocket); // When int localPort = serverSocket.getLocalPort(); BatchSource<String> socketSource ...
public static String toJson(Object obj) { try { return mapper.writeValueAsString(obj); } catch (JsonProcessingException e) { throw new NacosSerializationException(obj.getClass(), e); } }
@Test void testToJson1() { assertEquals("null", JacksonUtils.toJson(null)); assertEquals("\"string\"", JacksonUtils.toJson("string")); assertEquals("30", JacksonUtils.toJson(new BigDecimal(30))); assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", ...
public static double auc(double[] x, double[] y) { if (x.length != y.length) { throw new IllegalArgumentException("x and y must be the same length, x.length = " + x.length + ", y.length = " + y.length); } double output = 0.0; for (int i = 1; i < x.length; i++) { ...
@Test public void testAUC() { double output; try { output = Util.auc(new double[]{0.0,1.0},new double[]{0.0,1.0,2.0}); fail("Exception not thrown for mismatched lengths."); } catch (IllegalArgumentException e) { } try { output = Util.auc(new doub...
@Override @CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理 public void updateNotifyTemplate(NotifyTemplateSaveReqVO updateReqVO) { // 校验存在 validateNotifyTemplateExists(updateReqVO.getId()); // 校验站内信编码是否重复...
@Test public void testUpdateNotifyTemplate_notExists() { // 准备参数 NotifyTemplateSaveReqVO reqVO = randomPojo(NotifyTemplateSaveReqVO.class); // 调用, 并断言异常 assertServiceException(() -> notifyTemplateService.updateNotifyTemplate(reqVO), NOTIFY_TEMPLATE_NOT_EXISTS); }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { var triggers = annotations.stream() .filter(te -> { for (var trigger : KoraSchedulingAnnotationProcessor.triggers) { if (te.getQualifiedName().contentEquals(t...
@Test void testScheduledJdkAtFixedDelayTest() throws Exception { process(ScheduledJdkAtFixedDelayTest.class); }
@GetInitialRestriction public OffsetRange initialRestriction(@Element KafkaSourceDescriptor kafkaSourceDescriptor) { Map<String, Object> updatedConsumerConfig = overrideBootstrapServersConfig(consumerConfig, kafkaSourceDescriptor); TopicPartition partition = kafkaSourceDescriptor.getTopicPartition(); ...
@Test public void testInitialRestrictionWithException() throws Exception { thrown.expect(KafkaException.class); thrown.expectMessage("PositionException"); exceptionDofnInstance.initialRestriction( KafkaSourceDescriptor.of(topicPartition, null, null, null, null, ImmutableList.of())); }
public static Builder builder() { return new Builder(); }
@Test void testJsonDeserializeAndBuilder() throws Exception { String json = "{" + "\"service_id\":\"custom-service\"," + "\"max_tokens\":512," + "\"temperature\":0.8," + "\"top_p\":0.5," + "\"presence_penalty\":0.2," + "\"frequency_pena...
@Override public int hashCode() { int result = Objects.hash(method, paramDesc, returnClass, methodName, generic, attributeMap); result = 31 * result + Arrays.hashCode(compatibleParamSignatures); result = 31 * result + Arrays.hashCode(parameterClasses); result = 31 * result + Arrays.h...
@Test void testHashCode() { try { MethodDescriptor method2 = new ReflectionMethodDescriptor(DemoService.class.getDeclaredMethod("sayHello", String.class)); method.addAttribute("attr", "attr"); method2.addAttribute("attr", "attr"); Assertion...
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 shouldNotAcceptNegativeCorePoolSize() { new ExecutorConfig().setPoolSize(-1); }
public static void main(String[] args) { /* set up */ var charProto = new Character(); charProto.set(Stats.STRENGTH, 10); charProto.set(Stats.AGILITY, 10); charProto.set(Stats.ARMOR, 10); charProto.set(Stats.ATTACK_POWER, 10); var mageProto = new Character(Type.MAGE, charProto); magePro...
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public Page<InstanceConfig> findActiveInstanceConfigsByReleaseKey(String releaseKey, Pageable pageable) { return instanceConfigRepository.findByReleaseKeyAndDataChangeLastModifiedTimeAfter(releaseKey, getValidInstanceConfigDate(), pageable); }
@Test @Rollback public void testFindActiveInstanceConfigs() throws Exception { long someInstanceId = 1; long anotherInstanceId = 2; String someConfigAppId = "someConfigAppId"; String someConfigClusterName = "someConfigClusterName"; String someConfigNamespaceName = "someConfigNamespaceName"; ...
protected EventValuesWithLog extractEventParametersWithLog(Event event, Log log) { return staticExtractEventParametersWithLog(event, log); }
@Test public void testExtractEventParametersWithLogGivenATransactionReceipt() { final java.util.function.Function<String, Event> eventFactory = name -> new Event(name, emptyList()); final BiFunction<Integer, Event, Log> logFactory = (logIndex, event) -> ...
public Iterator<TrainTestFold<T>> split(Dataset<T> dataset, boolean shuffle) { int nsamples = dataset.size(); if (nsamples == 0) { throw new IllegalArgumentException("empty input data"); } if (nsplits > nsamples) { throw new IllegalArgumentException("cannot have n...
@Test public void testKFolderTwoSplits() { Dataset<MockOutput> data = getData(50); KFoldSplitter<MockOutput> kf = new KFoldSplitter<>(2,1); Iterator<KFoldSplitter.TrainTestFold<MockOutput>> itr = kf.split(data,false); while (itr.hasNext()) { KFoldSplitter.TrainTestFold<Mo...
public Map<String, Long> getFreeBytesOnTiers() { Map<String, Long> freeCapacityBytes = new HashMap<>(); for (Map.Entry<String, Long> entry : mUsage.mTotalBytesOnTiers.entrySet()) { freeCapacityBytes.put(entry.getKey(), entry.getValue() - mUsage.mUsedBytesOnTiers.get(entry.getKey())); } r...
@Test public void getFreeBytesOnTiers() { assertEquals(ImmutableMap.of(Constants.MEDIUM_MEM, Constants.KB * 2L, Constants.MEDIUM_SSD, Constants.KB * 2L), mInfo.getFreeBytesOnTiers()); }
public static boolean isTableNode(final String path) { return Pattern.compile(getMetaDataNode() + TABLES_PATTERN + TABLE_SUFFIX, Pattern.CASE_INSENSITIVE).matcher(path).find(); }
@Test void assertIsTableNode() { assertTrue(TableMetaDataNode.isTableNode("/metadata/foo_db/schemas/foo_schema/tables/foo_table")); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { super.doFilter(request, response, chain); return; } final HttpServletRequest httpRequest = (HttpServletRequest) reque...
@Test public void testNoHttp() throws IOException, ServletException { final ServletRequest request = createNiceMock(ServletRequest.class); final ServletResponse response = createNiceMock(ServletResponse.class); final FilterChain chain = createNiceMock(FilterChain.class); replay(request); replay(response); ...
static void clusterIdCommand(PrintStream stream, Admin adminClient) throws Exception { String clusterId = adminClient.describeCluster().clusterId().get(); if (clusterId != null) { stream.println("Cluster ID: " + clusterId); } else { stream.println("No cluster ID found. Th...
@Test public void testPrintClusterId() throws Exception { Admin adminClient = new MockAdminClient.Builder(). clusterId("QtNwvtfVQ3GEFpzOmDEE-w"). build(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ClusterTool.clusterIdCommand(new PrintStream(...
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldFailOnPersistentQueryLimitClauseStream() { // Given: final SingleStatementContext stmt = givenQuery("CREATE STREAM X AS SELECT * FROM TEST1 LIMIT 5;"); // Then: Exception exception = assertThrows(KsqlException.class, () -> { builder.buildStatement(stmt); ...
@NonNull public List<VFSConnectionDetails> getAllDetails( @NonNull ConnectionManager manager ) { return getProviders( manager ) .stream() .flatMap( provider -> { List<VFSConnectionDetails> providerDetails = provider.getConnectionDetails( manager ); return providerDetails != null ? prov...
@Test public void testGetAllDetailsReturnsAllDetailsFromAllVFSProvidersFromManager() { ConnectionProvider<? extends ConnectionDetails> provider1 = (ConnectionProvider<? extends ConnectionDetails>) mock( VFSConnectionProvider.class ); ConnectionProvider<? extends ConnectionDetails> provider2 = (Con...
@Override public Boolean mSet(Map<byte[], byte[]> tuple) { if (isQueueing() || isPipelined()) { for (Entry<byte[], byte[]> entry: tuple.entrySet()) { write(entry.getKey(), StringCodec.INSTANCE, RedisCommands.SET, entry.getKey(), entry.getValue()); } return...
@Test public void testMSet() { Map<byte[], byte[]> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(("test" + i).getBytes(), ("test" + i*100).getBytes()); } connection.mSet(map); for (Map.Entry<byte[], byte[]> entry : map.entrySet()) { ass...
@Override public Mono<byte[]> decrypt(byte[] encryptedMessage) { return Mono.just(this.keyPair) .map(KeyPair::getPrivate) .flatMap(privateKey -> { try { var cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT...
@Test void shouldFailToDecryptMessage() { StepVerifier.create(service.decrypt("invalid-bytes".getBytes())) .verifyError(InvalidEncryptedMessageException.class); }
Map<String, String> execute(ServerWebExchange exchange, StainingRule stainingRule) { if (stainingRule == null) { return Collections.emptyMap(); } List<StainingRule.Rule> rules = stainingRule.getRules(); if (CollectionUtils.isEmpty(rules)) { return Collections.emptyMap(); } Map<String, String> parsed...
@Test public void testMatchCondition() { Condition condition1 = new Condition(); condition1.setKey("${http.header.uid}"); condition1.setOperation(Operation.EQUALS.toString()); condition1.setValues(Collections.singletonList("1000")); Condition condition2 = new Condition(); condition2.setKey("${http.query.s...
@Override public List<Plugin> plugins() { List<Plugin> plugins = configurationParameters.get(PLUGIN_PROPERTY_NAME, s -> Arrays.stream(s.split(",")) .map(String::trim) .map(PluginOption::parse) .map(pluginOption -> (Plugin) pluginOption) .collec...
@Test void getPluginNamesWithPublishToken() { ConfigurationParameters config = new MapConfigurationParameters( Constants.PLUGIN_PUBLISH_TOKEN_PROPERTY_NAME, "some/token"); assertThat(new CucumberEngineOptions(config).plugins().stream() .map(Options.Plugin::pluginString) ...
public void forEach(BiConsumer<? super PropertyKey, ? super Object> action) { for (Map.Entry<PropertyKey, Object> entry : entrySet()) { action.accept(entry.getKey(), entry.getValue()); } }
@Test public void forEach() { Set<PropertyKey> expected = new HashSet<>(PropertyKey.defaultKeys()); Set<PropertyKey> actual = Sets.newHashSet(); mProperties.forEach((key, value) -> actual.add(key)); assertThat(actual, is(expected)); PropertyKey newKey = stringBuilder("forEachNew").build(); mP...
public void deschedule(Node<K, V> node) { unlink(node); node.setNextInVariableOrder(null); node.setPreviousInVariableOrder(null); }
@Test(dataProvider = "clock") public void deschedule_notScheduled(long clock) { timerWheel.nanos = clock; timerWheel.deschedule(new Timer(clock + 100)); }
public String formatDuration(Date then) { Duration duration = approximateDuration(then); return formatDuration(duration); }
@Test public void testFormatDuration() throws Exception { long tenMinMillis = java.util.concurrent.TimeUnit.MINUTES.toMillis(10); Date tenMinAgo = new Date(System.currentTimeMillis() - tenMinMillis); PrettyTime t = new PrettyTime(); String result = t.formatDuration(tenMinAgo); Assert...
@Override public LocalResourceId resolve(String other, ResolveOptions resolveOptions) { checkState(isDirectory(), "Expected the path is a directory, but had [%s].", pathString); checkArgument( resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) || resolveOptions.equals(StandardResol...
@Test public void testResolveHandleBadInputsInUnix() { if (SystemUtils.IS_OS_WINDOWS) { // Skip tests return; } assertEquals( toResourceIdentifier("/root/tmp/"), toResourceIdentifier("/root/").resolve("tmp/", StandardResolveOptions.RESOLVE_DIRECTORY)); }
@Override public Health health() { Map<String, Health> healths = rateLimiterRegistry.getAllRateLimiters().stream() .filter(this::isRegisterHealthIndicator) .collect(Collectors.toMap(RateLimiter::getName, this::mapRateLimiterHealth)); Status status = statusAggregator.getAggre...
@Test public void healthIndicatorMaxImpactCanBeOverridden() throws Exception { // given RateLimiterConfig config = mock(RateLimiterConfig.class); AtomicRateLimiter.AtomicRateLimiterMetrics metrics = mock(AtomicRateLimiter.AtomicRateLimiterMetrics.class); AtomicRateLimiter rateLimiter...
@Override public void addResponseCookie(Cookie cookie) { this.response.addHeader("Set-Cookie", WebContextHelper.createCookieHeader(cookie)); }
@Test public void testCookieExpires() { var mockResponse = new MockHttpServletResponse(); WebContext context = new JEEContext(request, mockResponse); Cookie c = new Cookie("thename","thevalue"); c.setMaxAge(1000); context.addResponseCookie(c); var header = mockRespon...
@Override public void onError(Throwable e) { _future.completeExceptionally(e); }
@Test public void testError() { CompletableFuture<String> future = new CompletableFuture<>(); CompletableFutureCallbackAdapter<String> adapter = new CompletableFutureCallbackAdapter<>(future); Throwable error = new IllegalArgumentException("exception"); adapter.onError(error); assertTrue(future....
@Override public <T> T convert(DataTable dataTable, Type type) { return convert(dataTable, type, false); }
@Test void convert_to_map_of_primitive_to_list_of_primitive() { DataTable table = parse("", "| KMSY | 29.993333 | -90.258056 |", "| KSFO | 37.618889 | -122.375 |", "| KSEA | 47.448889 | -122.309444 |", "| KJFK | 40.639722 | -73.778889 |"); Map<St...
public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant::node()") || xpath.equals("/descendant:node()")) { // f...
@Test public void testText() { Matcher matcher = parser.parse("/text()"); assertTrue(matcher.matchesText()); assertFalse(matcher.matchesElement()); assertFalse(matcher.matchesAttribute(NS, "name")); assertEquals(Matcher.FAIL, matcher.descend(NS, "name")); }
@Override public Optional<FieldTypes> get(final String fieldName) { return Optional.ofNullable(get(ImmutableSet.of(fieldName)).get(fieldName)); }
@Test public void getSingleField() { dbService.save(createDto("graylog_0", "abc", Collections.emptySet())); dbService.save(createDto("graylog_1", "xyz", Collections.emptySet())); dbService.save(createDto("graylog_2", "xyz", Collections.emptySet())); dbService.save(createDto("graylog_...
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException { byte[] bytes = pollEntryBytes(timeout); if (bytes == null) { return null; } return DLQEntry.deserialize(bytes); }
@Test public void testFlushAfterWriterClose() throws Exception { Event event = new Event(); event.setField("T", generateMessageContent(PAD_FOR_BLOCK_SIZE_EVENT/8)); Timestamp timestamp = new Timestamp(); try (DeadLetterQueueWriter writeManager = DeadLetterQueueWriter ...
public static int min(int a, int b, int c) { return Math.min(Math.min(a, b), c); }
@Test public void testMin_doubleArrArr() { System.out.println("min"); double[][] A = { {0.7220180, 0.07121225, 0.6881997}, {-0.2648886, -0.89044952, 0.3700456}, {-0.6391588, 0.44947578, 0.6240573} }; assertEquals(-0.89044952, MathEx.min(A), 1E-7); ...
@SuppressWarnings("unchecked") public final V getIfExists() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap != null) { Object v = threadLocalMap.indexedVariable(index); if (v != InternalThreadLocalMap.UNSET) { re...
@Test public void testGetIfExists() { FastThreadLocal<Boolean> threadLocal = new FastThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.TRUE; } }; assertNull(threadLocal.getIfExists()); assertTrue(...
@Override public void checkTopicAccess( final KsqlSecurityContext securityContext, final String topicName, final AclOperation operation ) { authorizationProvider.checkPrivileges( securityContext, AuthObjectType.TOPIC, topicName, ImmutableList.of(operation) )...
@Test public void shouldCheckTopicPrivilegesOnProvidedAccessValidator() { // When accessValidator.checkTopicAccess(securityContext, "topic1", AclOperation.WRITE); // Then verify(authorizationProvider, times(1)) .checkPrivileges( securityContext, ...
public Double asDouble(Map<String, ValueReference> parameters) { switch (valueType()) { case DOUBLE: if (value() instanceof Number) { return ((Number) value()).doubleValue(); } throw new IllegalStateException("Expected value referen...
@Test public void asDouble() { assertThat(ValueReference.of(1.0d).asDouble(Collections.emptyMap())).isEqualTo(1.0d); assertThatThrownBy(() -> ValueReference.of("Test").asDouble(Collections.emptyMap())) .isInstanceOf(IllegalStateException.class) .hasMessage("Expected v...
void truncateTable() throws KettleDatabaseException { if ( !meta.isPartitioningEnabled() && !meta.isTableNameInField() ) { // Only the first one truncates in a non-partitioned step copy // if ( meta.truncateTable() && ( ( getCopy() == 0 && getUniqueStepNrAcrossSlaves() == 0 ) || !Utils.isE...
@Test public void testTruncateTable_on_PartitionId() throws Exception { when( tableOutputMeta.truncateTable() ).thenReturn( true ); when( tableOutputSpy.getCopy() ).thenReturn( 1 ); when( tableOutputSpy.getUniqueStepNrAcrossSlaves() ).thenReturn( 0 ); when( tableOutputSpy.getPartitionID() ).thenReturn...
@Override public Result search(Query query, Execution execution) { Result mergedResults = execution.search(query); var targets = getTargets(query.getModel().getSources(), query.properties()); warnIfUnresolvedSearchChains(extractErrors(targets), mergedResults.hits()); var prunedTarg...
@Test void custom_federation_target() { ComponentId targetSelectorId = ComponentId.fromString("TargetSelector"); ComponentRegistry<TargetSelector> targetSelectors = new ComponentRegistry<>(); targetSelectors.register(targetSelectorId, new TestTargetSelector()); FederationSearcher se...
@Override public void write(T record) { recordConsumer.startMessage(); try { messageWriter.writeTopLevelMessage(record); } catch (RuntimeException e) { Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record; LOG.error("Cannot write message...
@Test public void testOptionalInnerMessage() throws Exception { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); ProtoWriteSupport<TestProtobuf.MessageA> instance = createReadConsumerInstance(TestProtobuf.MessageA.class, readConsumerMock); TestProtobuf.MessageA.Builder msg = ...
public static boolean isIPv6Address(final String input) { return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input) || isLinkLocalIPv6WithZoneIndex(input) || isIPv6IPv4MappedAddress(input) || isIPv6MixedAddress(input); }
@Test public void isIPv6Address() { assertThat(NetAddressValidatorUtil.isIPv6Address("2000:0000:0000:0000:0001:2345:6789:abcd")).isTrue(); assertThat(NetAddressValidatorUtil.isIPv6Address("2001:DB8:0:0:8:800:200C:417A")).isTrue(); assertThat(NetAddressValidatorUtil.isIPv6Address("2001:DB8::8...
@Override @MethodNotAvailable public void loadAll(boolean replaceExistingValues) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testLoadAll() { adapterWithLoader.loadAll(true); }
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_failure() { expectFailureWhenTestingThat(array(1.1f, JUST_OVER_2POINT2, 3.3f)) .usingExactEquality() .contains(2.2f); assertFailureKeys("value of", "expected to contain", "testing whether", "but was"); assertFailureValue("expected to contain", ...
public String process(String preResolved, ParamHandler paramsHandler) { ReaderState state = ReaderState.NOT_IN_PATTERN; for (int i = 0; i < preResolved.length(); i++) { state = state.interpret(preResolved.charAt(i), paramsHandler); } paramsHandler.handleAfterResolution(state)...
@Test public void shouldClearPatternWhenParameterCannotBeResolved() throws Exception { ParamStateMachine stateMachine = new ParamStateMachine(); doThrow(new IllegalStateException()).when(handler).handlePatternFound(any(StringBuilder.class)); try { stateMachine.process("#{pattern...
String resolve() throws IOException { String from = String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName()); if (!Strings.isNullOrEmpty(options.getPrismLocation())) { checkArgument( !options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX), "P...
@Test public void givenHttpPrismLocationOption_thenResolves() throws IOException { assertThat(Files.exists(DESTINATION_DIRECTORY)).isFalse(); PrismPipelineOptions options = options(); options.setPrismLocation( "https://github.com/apache/beam/releases/download/v2.57.0/apache_beam-v2.57.0-prism-darw...
public static boolean isKerberosSecurityEnabled(UserGroupInformation ugi) { return UserGroupInformation.isSecurityEnabled() && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.KERBEROS; }
@Test public void isKerberosSecurityEnabled_NoKerberos_ReturnsFalse() { UserGroupInformation.setConfiguration( getHadoopConfigWithAuthMethod(AuthenticationMethod.PROXY)); UserGroupInformation userWithAuthMethodOtherThanKerberos = createTestUser(AuthenticationMethod.PR...
public static String get(String urlString, Charset customCharset) { return HttpRequest.get(urlString).charset(customCharset).execute().body(); }
@Test @Disabled public void getTest2() { // 此链接较为特殊,User-Agent去掉后进入一个JS跳转页面,如果设置了,需要开启302跳转 // 自定义的默认header无效 final String result = HttpRequest .get("https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101457313&redirect_uri=http%3A%2F%2Fwww.benmovip.com%2Fpay-cloud%2Fqqlogin%2FgetCode&stat...
@Override protected List<MatchResult> match(List<String> specs) throws IOException { List<GcsPath> gcsPaths = toGcsPaths(specs); List<GcsPath> globs = Lists.newArrayList(); List<GcsPath> nonGlobs = Lists.newArrayList(); List<Boolean> isGlobBooleans = Lists.newArrayList(); for (GcsPath path : gcs...
@Test public void testMatch() throws Exception { Objects modelObjects = new Objects(); List<StorageObject> items = new ArrayList<>(); // A directory items.add(new StorageObject().setBucket("testbucket").setName("testdirectory/")); // Files within the directory items.add(createStorageObject("g...
public Stream<SqlMigration> getMigrations() { SqlMigrationProvider migrationProvider = getMigrationProvider(); try { final Map<String, SqlMigration> commonMigrations = getCommonMigrations(migrationProvider).stream().collect(toMap(SqlMigration::getFileName, m -> m)); final Map<St...
@Test void testGetMigrations() { final DatabaseMigrationsProvider databaseCreator = new DatabaseMigrationsProvider(null); final Stream<SqlMigration> databaseSpecificMigrations = databaseCreator.getMigrations(); assertThat(databaseSpecificMigrations).anyMatch(migration -> migration.getFileNam...
@Override public int hashCode() { return MessageIdAdvUtils.hashCode(this); }
@Test public void hashCodeUnbatchedTest() { BatchMessageIdImpl batchMsgId1 = new BatchMessageIdImpl(0, 0, 0, -1); BatchMessageIdImpl batchMsgId2 = new BatchMessageIdImpl(1, 1, 1, -1); MessageIdImpl msgId1 = new MessageIdImpl(0, 0, 0); MessageIdImpl msgId2 = new MessageIdImpl(1, 1, 1...
@ProcessElement public void processElement( @Element KV<ByteString, ChangeStreamRecord> changeStreamRecordKV, OutputReceiver<KV<ByteString, ChangeStreamMutation>> receiver) { ChangeStreamRecord inputRecord = changeStreamRecordKV.getValue(); if (inputRecord instanceof ChangeStreamMutation) { ...
@Test public void shouldOutputCloseStreams() { // This shouldn't happen but if it were to we wouldn't want the CloseStreams to be returned to // users CloseStream closeStream = mock(CloseStream.class); doFn.processElement(KV.of(ByteString.copyFromUtf8("test"), closeStream), outputReceiver); verify...
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } try { TemporalAccessor parsed = FEEL_TIME.parse(val); i...
@Test void invokeTemporalAccessorParamDate() { FunctionTestUtil.assertResult(timeFunction.invoke(LocalDate.of(2017, 6, 12)), OffsetTime.of(0, 0, 0, 0, ZoneOffset.UTC)); }
@Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { super.pre(span, exchange, endpoint); span.setTag(TagConstants.DB_SYSTEM, ELASTICSEARCH_DB_TYPE); Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri()); if (queryParameter...
@Test public void testPre() { String indexName = "twitter"; String cluster = "local"; Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpoint...
public List<VespaConfigChangeAction> validate() { return currentDocType.getAllFields().stream(). map(field -> createFieldChange(field, nextDocType)). filter(fieldChange -> fieldChange.valid() && fieldChange.changedType()). map(fieldChange -> VespaRefeedAction.of(i...
@Test void requireThatChangingTargetTypeOfReferenceFieldIsNotOK() { var validator = new DocumentTypeChangeValidator(ClusterSpec.Id.from("test"), createDocumentTypeWithReferenceField("oldDoc"), createDocumentTypeWithReferenceField("newDoc")); List<VespaConfigChangeActi...
public static byte[] parseHigh2Low6Bytes(byte b) { return new byte[] { (byte) ((b >> 6)), // 右移6位,只取前2bit的值 (byte) ((b & 0x3f)) // 只取后面6bit的值,前面两位补0 }; }
@Test public void parseHigh2Low6Bytes() { byte b = 117; // = 1*64 + 53 byte[] bs = CodecUtils.parseHigh2Low6Bytes(b); Assert.assertEquals(bs[0], 1); Assert.assertEquals(bs[1], 53); }
@Override public Mono<ReserveUsernameHashResponse> reserveUsernameHash(final ReserveUsernameHashRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); if (request.getUsernameHashesCount() == 0) { throw Status.INVALID_ARGUMENT .withD...
@Test void reserveUsernameHash() { final Account account = mock(Account.class); when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI)) .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNA...
protected void replaceFiles(List<MappedFile> mappedFileList, TopicPartitionLog current, TopicPartitionLog newLog) { MappedFileQueue dest = current.getLog(); MappedFileQueue src = newLog.getLog(); long beginTime = System.nanoTime(); // List<String> fileNameToReplace = mappedFileL...
@Test public void testReplaceFiles() throws IOException, IllegalAccessException { Assume.assumeFalse(MixAll.isWindows()); CompactionLog clog = mock(CompactionLog.class); doCallRealMethod().when(clog).replaceFiles(anyList(), any(CompactionLog.TopicPartitionLog.class), any(Compacti...
public Resource getIncrementAllocation() { Long memory = null; Integer vCores = null; Map<String, Long> others = new HashMap<>(); ResourceInformation[] resourceTypes = ResourceUtils.getResourceTypesArray(); for (int i=0; i < resourceTypes.length; ++i) { String name = resourceTypes[i].getName()...
@Test(expected=IllegalArgumentException.class) public void testAllocationIncrementInvalidUnit() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RESOURCE_TYPES + "." + ResourceInformation.MEMORY_MB.getName() + FairSchedulerConfiguration.INCREMENT_ALLOCATI...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 1) { if ("withZone".equals(methodName)) { return new SelJodaDateTimeFormatter( val.withZone(((SelJodaDateTimeZone) args[0]).getInternalVal())); } else if ("parseDateTime".equals(methodName)) { ...
@Test(expected = ClassCastException.class) public void testInvalidCallArg() { one.call("withZone", new SelType[] {SelType.NULL}); }
public static Expression convert(Filter[] filters) { Expression expression = Expressions.alwaysTrue(); for (Filter filter : filters) { Expression converted = convert(filter); Preconditions.checkArgument( converted != null, "Cannot convert filter to Iceberg: %s", filter); expression =...
@Test public void testTimestampFilterConversion() { Instant instant = Instant.parse("2018-10-18T00:00:57.907Z"); Timestamp timestamp = Timestamp.from(instant); long epochMicros = ChronoUnit.MICROS.between(Instant.EPOCH, instant); Expression instantExpression = SparkFilters.convert(GreaterThan.apply("...
public Map<String, Partition> getPartitionByNames(Table table, List<String> partitionNames) { String dbName = ((HiveMetaStoreTable) table).getDbName(); String tblName = ((HiveMetaStoreTable) table).getTableName(); return metastore.getPartitionsByNames(dbName, tblName, partitionNames); }
@Test public void testGetPartitionByNames() throws AnalysisException { com.starrocks.catalog.Table table = hmsOps.getTable("db1", "table1"); HiveTable hiveTable = (HiveTable) table; PartitionKey hivePartitionKey1 = PartitionUtil.createPartitionKey( Lists.newArrayList("1"), hi...