focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Input<DefaultIssue> create(Component component) { if (component.getType() == Component.Type.PROJECT) { return new ProjectTrackerBaseLazyInput(dbClient, issuesLoader, component); } if (component.getType() == Component.Type.DIRECTORY) { // Folders have no issues return new EmptyTrack...
@Test public void create_returns_Input_which_retrieves_issues_of_specified_file_component_when_it_has_no_original_file() { underTest.create(FILE).getIssues(); verify(issuesLoader).loadOpenIssues(FILE_UUID); }
@Override public String digest(final Object plainValue) { return null == plainValue ? null : DigestUtils.md5Hex(plainValue + salt); }
@Test void assertDigest() { assertThat(digestAlgorithm.digest("test"), is("098f6bcd4621d373cade4e832627b4f6")); }
@Override public boolean supportsSubqueriesInComparisons() { return false; }
@Test void assertSupportsSubqueriesInComparisons() { assertFalse(metaData.supportsSubqueriesInComparisons()); }
public String toBasicHeader(){ return "Basic " + new String(Base64.getEncoder().encode((getUser() + ":" + getPass()). getBytes(Charset.defaultCharset())), Charset.defaultCharset()); }
@Test public void testToBasicHeader() { Authorization basicAuthorization = new Authorization("http://example.com", "foo", "bar", null, "Test Realm", Mechanism.BASIC); assertThat(basicAuthorization.toBasicHeader(), CoreMatchers.is("Basic Zm9vOmJhcg==")); }
static String indent(String item) { // '([^']|'')*': Matches the escape sequence "'...'" where the content between "'" // characters can contain anything except "'" unless its doubled (''). // // Then each match is checked. If it starts with "'", it's left unchanged // (escaped ...
@Test void testSimpleIndent() { String sourceQuery = "SELECT * FROM source_t"; String s = String.format( "SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery)); assertThat(s) .isEqualTo("SELECT * FROM (\n" + " SELECT...
static void populateAllowCommentAttribute(ITemplateContext context, boolean allowComment) { if (Contexts.isWebContext(context)) { IWebContext webContext = Contexts.asWebContext(context); webContext.getExchange() .setAttributeValue(COMMENT_ENABLED_MODEL_ATTRIBUTE, allowCom...
@Test void populateAllowCommentAttribute() { WebEngineContext webContext = mock(WebEngineContext.class); IWebExchange webExchange = mock(IWebExchange.class); when(webContext.getExchange()).thenReturn(webExchange); CommentEnabledVariableProcessor.populateAllowCommentAttribute(webCont...
public static LocalDateTime formatLocalDateTimeFromTimestampBySystemTimezone(final Long timestamp) { return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, OffsetDateTime.now().getOffset()); }
@Test public void testFormatLocalDateTimeFromTimestampBySystemTimezone() { LocalDateTime localDateTime1 = LocalDateTime.now(); LocalDateTime localDateTime2 = DateUtils.formatLocalDateTimeFromTimestampBySystemTimezone(ZonedDateTime.of(localDateTime1, ZoneId.systemDefault()).toInstant().toEpochMilli()...
public static ByteBuf copyShort(int value) { ByteBuf buf = buffer(2); buf.writeShort(value); return buf; }
@Test public void testWrapShortFromShortArray() { ByteBuf buffer = copyShort(new short[]{1, 4}); assertEquals(4, buffer.capacity()); assertEquals(1, buffer.readShort()); assertEquals(4, buffer.readShort()); assertFalse(buffer.isReadable()); buffer.release(); ...
@Override public String toString() { StringBuilder sb = new StringBuilder(); if (StringUtil.isNotEmpty(msg)) { sb.append(msg); } int tempCount = 0; for (Map.Entry<String, Object> kv : kvs.entrySet()) { tempCount++; Object value = kv.getValu...
@Test public void testToStringShouldHaveAnEmptyMessage() { assertEquals(Strings.EMPTY, logMessage.toString()); }
public InputBuffer(BufferType type, int inputSize) throws IOException { final int capacity = inputSize; this.type = type; if (capacity > 0) { switch (type) { case DIRECT_BUFFER: this.byteBuffer = bufferPool.getBuffer(capacity); this.byteBuffer.order(ByteOrder.BIG_ENDIAN); ...
@Test public void testInputBuffer() throws IOException { final int size = 100; final InputBuffer input1 = new InputBuffer(BufferType.DIRECT_BUFFER, size); assertThat(input1.getType()).isEqualTo(BufferType.DIRECT_BUFFER); assertThat(input1.position()).isZero(); assertThat(input1.length()).isZero()...
public static String createUniqID() { char[] sb = new char[LEN * 2]; System.arraycopy(FIX_STRING, 0, sb, 0, FIX_STRING.length); long current = System.currentTimeMillis(); if (current >= nextStartTime) { setStartTime(current); } int diff = (int)(current - start...
@Test public void testGetCountFromID() { String uniqID = MessageClientIDSetter.createUniqID(); String uniqID2 = MessageClientIDSetter.createUniqID(); String idHex = uniqID.substring(uniqID.length() - 4); String idHex2 = uniqID2.substring(uniqID2.length() - 4); int s1 = Intege...
static URI cleanUrl(String originalUrl, String host) { return URI.create(originalUrl.replaceFirst(host, "")); }
@Test void cleanUrl() throws IOException { URI uri = RibbonClient.cleanUrl("http://myservice/questions/answer/123", "myservice"); assertThat(uri.toString()).isEqualTo("http:///questions/answer/123"); }
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void getOneWorker() throws Exception { WorkerLocationPolicy policy = WorkerLocationPolicy.Factory.create(mConf); assertTrue(policy instanceof KetamaHashPolicy); // Prepare a worker list WorkerClusterView workers = new WorkerClusterView(Arrays.asList( new WorkerInfo() ....
@Override public synchronized boolean tryReturnRecordAt( boolean isAtSplitPoint, @Nullable ShufflePosition groupStart) { if (lastGroupStart == null && !isAtSplitPoint) { throw new IllegalStateException( String.format("The first group [at %s] must be at a split point", groupStart.toString()))...
@Test public void testFirstRecordNonSplitPoint() throws Exception { GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker(ofBytes(3, 0, 0), ofBytes(5, 0, 0)); expected.expect(IllegalStateException.class); tracker.tryReturnRecordAt(false, ofBytes(3, 4, 5)); }
@Override public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) throws AccessDeniedException { if(input.getOptionValues(action.name()).length == 2) { final String path = input.getOptionValues(action.name())[1]; // This only applies to ...
@Test public void testNoLocalInOptionsUploadFile() throws Exception { final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "rackspace://cdn.cyberduck.ch/remote"}); final Set<TransferItem> found ...
public List<KuduPredicate> convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testEqDateTime() { ConstantOperator value = ConstantOperator.createDatetime(LocalDateTime.of(2024, 1, 1, 0, 0)); ScalarOperator op = new BinaryPredicateOperator(BinaryType.EQ, F4, value); List<KuduPredicate> result = CONVERTER.convert(op); Assert.assertEquals(result...
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) { return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs)); }
@Test public void testGroupingKeyTypeWithEvolvedIntoUnpartitionedSpecV2Table() { TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V2_FORMAT_VERSION); table.updateSpec().removeField("data").commit(); assertThat(table.specs()).hasSize(2); StructType expec...
public static void cleanDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } cleanDirectoryImpl(directory.toPath()); }
@Test public void cleanDirectory_follows_symlink_to_target_directory() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path target = temporaryFolder.newFolder().toPath(); Path symToDir = Files.createSymbolicLink(temporaryFolder.newFolder().toPath().resolve("sym_to_dir"), target); Path childFi...
private void ensureRoleNamesAnno(User user) { roleService.getRolesByUsername(user.getMetadata().getName()) .collectList() .map(JsonUtils::objectToJson) .doOnNext(roleNamesJson -> { var annotations = Optional.ofNullable(user.getMetadata().getAnnotations()) ...
@Test void ensureRoleNamesAnno() { when(roleService.getRolesByUsername("fake-user")).thenReturn(Flux.just("fake-role")); when(client.fetch(eq(User.class), eq("fake-user"))) .thenReturn(Optional.of(user("fake-user"))); when(externalUrlSupplier.get()).thenReturn(URI.create("/")); ...
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) { ServletRequest wsRequest = new ServletRequest(request); ServletResponse wsResponse = new ServletResponse(response); webServiceEngine.execute(wsRequest, wsResponse); }
@Test public void execute_ws() { underTest = new WebServiceFilter(webServiceEngine); underTest.doFilter(new JavaxHttpRequest(request), new JavaxHttpResponse(response), chain); verify(webServiceEngine).execute(any(), any()); }
public static Date addTimeToDate( Date input, String time, String dateFormat ) throws Exception { if ( Utils.isEmpty( time ) ) { return input; } if ( input == null ) { return null; } String dateformatString = NVL( dateFormat, "HH:mm:ss" ); int t = decodeTime( time, dateformatString )...
@Test public void testAddTimeToDate() throws Exception { final Date date = new Date( 1447252914241L ); assertNull( Const.addTimeToDate( null, null, null ) ); assertEquals( date, Const.addTimeToDate( date, null, null ) ); assertEquals( 1447256637241L, Const.addTimeToDate( date, "01:02:03", "HH:mm:ss" )...
public static MetadataUpdate fromJson(String json) { return JsonUtil.parse(json, MetadataUpdateParser::fromJson); }
@Test public void testAddViewVersionFromJson() { String action = MetadataUpdateParser.ADD_VIEW_VERSION; long timestamp = 123456789; ViewVersion viewVersion = ImmutableViewVersion.builder() .versionId(23) .timestampMillis(timestamp) .schemaId(4) .putS...
public static void checkProjectKey(String keyCandidate) { checkArgument(isValidProjectKey(keyCandidate), MALFORMED_KEY_MESSAGE, keyCandidate, ALLOWED_CHARACTERS_MESSAGE); }
@Test public void checkProjectKey_fail_if_only_digit() { assertThatThrownBy(() -> ComponentKeys.checkProjectKey("0123")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Malformed key for '0123'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit."); }
public boolean isAfter(VectorClock other) { boolean anyTimestampGreater = false; for (Entry<UUID, Long> otherEntry : other.replicaTimestamps.entrySet()) { final UUID replicaId = otherEntry.getKey(); final Long otherReplicaTimestamp = otherEntry.getValue(); final Long ...
@Test public void testIsAfter() { assertFalse(vectorClock().isAfter(vectorClock())); assertTrue(vectorClock(uuidParams[0], 1).isAfter(vectorClock())); assertFalse(vectorClock(uuidParams[0], 1).isAfter(vectorClock(uuidParams[0], 1))); assertFalse(vectorClock(uuidParams[0], 1).isAfter(...
@Override public List<TransferItem> list(final Session<?> session, final Path directory, final Local local, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List children for %s", directory));...
@Test public void testDownloadDuplicateNameFolderAndFile() throws Exception { final Path parent = new Path("t", EnumSet.of(Path.Type.directory)); final Transfer t = new DownloadTransfer(new Host(new TestProtocol()), parent, new NullLocal(System.getProperty("java.io.tmpdir"))); final NullSess...
@Override public Object get(int fieldNum) { try { StructField fref = soi.getAllStructFieldRefs().get(fieldNum); return HCatRecordSerDe.serializeField( soi.getStructFieldData(wrappedObject, fref), fref.getFieldObjectInspector()); } catch (SerDeException e) { throw new Illega...
@Test public void testGetWithName() throws Exception { TypeInfo ti = getTypeInfo(); HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector(ti)); HCatSchema schema = HCatSchemaUtils.getHCatSchema(ti) .get(0).getStructSubSchema(); Assert.assertEquals(INT_CONST, ((I...
@Override public AppsInfo getApps(HttpServletRequest hsr, String stateQuery, Set<String> statesQuery, String finalStatusQuery, String userQuery, String queueQuery, String count, String startedBegin, String startedEnd, String finishBegin, String finishEnd, Set<String> applicationTypes, Set<Stri...
@Test public void testGetApplicationsReport() { AppsInfo responseGet = interceptor.getApps(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); Assert.assertNotNull(responseGet); Assert.assertEquals(NUM_SUBCLUSTER, responseGet.getApps().size()); // The m...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void issueIA74K2Test() { UserAgent ua = UserAgentUtil.parse( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) MicroMessenger/6.8.0(0x16080000) MacWechat/3.8.7(0x13080710) Safari/605.1.15 NetType/WIFI"); assertEquals("MicroMessenger", ua.getBrowser().toStrin...
@Override public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException { synchronized (redoService.getRegisteredInstances()) { List<Instance> retainInstance = getRetainInstance(serviceName, groupName, instances); ...
@Test void testBatchDeregisterServiceWithoutCacheData() throws NacosException { assertThrows(NacosException.class, () -> { List<Instance> instanceList = new ArrayList<>(); instance.setHealthy(true); instanceList.add(instance); client.batchDeregisterService(SER...
public String get(Component c) { return get(Group.Alphabetic, c); }
@Test public void testSubsumeSurplusComponentInSuffix() { PersonName pn = new PersonName("Adams^John Robert Quincy^^Rev.^B.A.^M.Div.", true); assertEquals("Adams", pn.get(PersonName.Component.FamilyName)); assertEquals("John Robert Quincy", pn.get(PersonName.Component.GivenName)); as...
public PlainAccessConfig createAclAccessConfigMap(PlainAccessConfig existedAccountMap, PlainAccessConfig plainAccessConfig) { PlainAccessConfig newAccountsMap = null; if (existedAccountMap == null) { newAccountsMap = new PlainAccessConfig(); } else { newAccountsM...
@Test public void createAclAccessConfigMapTest() { PlainAccessConfig existedAccountMap = new PlainAccessConfig(); plainAccessConfig.setAccessKey("admin123"); plainAccessConfig.setSecretKey("12345678"); plainAccessConfig.setWhiteRemoteAddress("192.168.1.1"); plainAccessConfig....
public static DLPDeidentifyText.Builder newBuilder() { return new AutoValue_DLPDeidentifyText.Builder(); }
@Test public void throwsExceptionWhenBatchSizeIsTooLarge() { assertThrows( String.format( "Batch size is too large! It should be smaller or equal than %d.", DLPDeidentifyText.DLP_PAYLOAD_LIMIT_BYTES), IllegalArgumentException.class, () -> DLPDeidentifyTe...
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; ...
@Test public void decodeFailsWithoutShortMessage() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"example.org\"" + "}"; final RawMessage rawMessage = new RawMessage(json.getBytes(StandardCharsets.UTF_8)); ...
public Response request(Request request) throws NacosException { return request(request, rpcClientConfig.timeOutMills()); }
@Test void testRequestWhenResponseErrorThenThrowException() throws NacosException { assertThrows(NacosException.class, () -> { rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); rpcClient.currentConnection = connection; doReturn(new ErrorResponse()).when(connection)....
@Override public RemoteData.Builder serialize() { RemoteData.Builder remoteBuilder = RemoteData.newBuilder(); remoteBuilder.addDataObjectStrings(count.toStorageData()); remoteBuilder.addDataObjectStrings(summation.toStorageData()); remoteBuilder.addDataLongs(getTimeBucket()); ...
@Test public void testSerialize() { function.accept( MeterEntity.newService("request_count", Layer.GENERAL), build(asList("200", "404"), asList(10L, 2L))); AvgLabeledFunction function2 = Mockito.spy(AvgLabeledFunction.class); function2.deserialize(function.serialize().build()); ...
@Override public Map<String, String> loadStreamTitles(Collection<String> streamIds) { if (streamIds.isEmpty()) { return Map.of(); } final var streamObjectIds = streamIds.stream().map(ObjectId::new).toList(); final var cursor = collection(StreamImpl.class).find( ...
@Test @MongoDBFixtures("someStreamsWithAlertConditions.json") public void loadStreamTitles() { final var result = streamService.loadStreamTitles(Set.of("565f02223b0c25a537197af2", "559d14663b0cf26a15ee0f01")); assertThat(result).hasSize(2); assertThat(result.get("565f02223b0c25a537197af...
public Connection connection(Connection connection) { // It is common to implement both interfaces if (connection instanceof XAConnection) { return xaConnection((XAConnection) connection); } return TracingConnection.create(connection, this); }
@Test void connection_wrapsXaInput() { abstract class Both implements XAConnection, Connection { } assertThat(jmsTracing.connection(mock(Both.class))) .isInstanceOf(XAConnection.class); }
@Override @Transactional(value="defaultTransactionManager") public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) throws AuthenticationException, InvalidClientException { if (authentication != null && authentication.getOAuth2Request() != null) { // look up our client OAuth2Requ...
@Test public void createAccessToken_checkAttachedAuthentication() { AuthenticationHolderEntity authHolder = mock(AuthenticationHolderEntity.class); when(authHolder.getAuthentication()).thenReturn(authentication); when(authenticationHolderRepository.save(any(AuthenticationHolderEntity.class))).thenReturn(authHol...
@Override public <X> TypeInformation<X> getTypeAt(String fieldExpression) { Matcher matcher = PATTERN_NESTED_FIELDS.matcher(fieldExpression); if (!matcher.matches()) { if (fieldExpression.equals(ExpressionKeys.SELECT_ALL_CHAR) || fieldExpression.equals(ExpressionKeys....
@Test void testGetTypeAt() { RowTypeInfo typeInfo = new RowTypeInfo(typeList); assertThat(typeInfo.getFieldNames()).isEqualTo(new String[] {"f0", "f1", "f2"}); assertThat(typeInfo.getTypeAt("f2")).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); assertThat(typeInfo.getTypeAt("f1.f0")).is...
public static String substVars(String val, PropertyContainer pc1) { return substVars(val, pc1, null); }
@Test public void detectCircularReferencesInDefault() { context.putProperty("A", "${B:-${A}}"); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${B} --> ${A}]"); OptionHelper.substVars("${A}",...
@Deprecated public Expression createExpression(String expression) { return createExpression(expression, new ParsingOptions()); }
@Test(timeOut = 2_000) public void testPotentialUnboundedLookahead() { SQL_PARSER.createExpression("(\n" + " 1 * -1 +\n" + " 1 * -2 +\n" + " 1 * -3 +\n" + " 1 * -4 +\n" + " 1 * -5 +\n" + ...
@Override public List<ParsedStatement> parse(final String sql) { return primaryContext.parse(sql); }
@Test public void shouldNotEnforceTopicExistenceWhileParsing() { setupKsqlEngineWithSharedRuntimeEnabled(); final String runScriptContent = "CREATE STREAM S1 (COL1 BIGINT, COL2 VARCHAR) " + "WITH (KAFKA_TOPIC = 's1_topic', VALUE_FORMAT = 'JSON', KEY_FORMAT = 'KAFKA');\n" + "CREATE TABLE T1 AS...
@Override public void updateGroup(MemberGroupUpdateReqVO updateReqVO) { // 校验存在 validateGroupExists(updateReqVO.getId()); // 更新 MemberGroupDO updateObj = MemberGroupConvert.INSTANCE.convert(updateReqVO); memberGroupMapper.updateById(updateObj); }
@Test public void testUpdateGroup_success() { // mock 数据 MemberGroupDO dbGroup = randomPojo(MemberGroupDO.class); groupMapper.insert(dbGroup);// @Sql: 先插入出一条存在的数据 // 准备参数 MemberGroupUpdateReqVO reqVO = randomPojo(MemberGroupUpdateReqVO.class, o -> { o.setId(dbGrou...
@Override public String getCommandName() { return COMMAND_NAME; }
@Test public void linuxCmdExecuted() throws IOException, AlluxioException, NoSuchFieldException, IllegalAccessException { CollectEnvCommand cmd = new CollectEnvCommand(FileSystemContext.create()); // Write to temp dir File targetDir = InfoCollectorTestUtils.createTemporaryDirectory(); Comma...
static public String jsonEscapeString(String input) { int length = input.length(); int lenthWithLeeway = (int) (length * 1.1); StringBuilder sb = new StringBuilder(lenthWithLeeway); for (int i = 0; i < length; i++) { final char c = input.charAt(i); String escaped...
@Test public void testEscapingLF() { String input = "{\nhello: \"wo\nrld\"}"; System.out.println(input); assertEquals("{\\nhello: "+'\\'+'"'+"wo\\nrld\\\"}", JsonEscapeUtil.jsonEscapeString(input)); }
public BeamFnApi.InstructionResponse.Builder finalizeBundle(BeamFnApi.InstructionRequest request) throws Exception { String bundleId = request.getFinalizeBundle().getInstructionId(); Collection<CallbackRegistration> callbacks = bundleFinalizationCallbacks.remove(bundleId); if (callbacks == null) { ...
@Test public void testFinalizationIgnoresMissingBundleIds() throws Exception { FinalizeBundleHandler handler = new FinalizeBundleHandler(Executors.newCachedThreadPool()); assertEquals(SUCCESSFUL_RESPONSE, handler.finalizeBundle(requestFor("test")).build()); }
private String setField(BufferedReader reader) throws IOException { String targetObjectId = reader.readLine(); String fieldName = reader.readLine(); String value = reader.readLine(); reader.readLine(); // read EndOfCommand; Object valueObject = Protocol.getObject(value, this.gateway); Object object = gate...
@Test public void testSetField() { String inputCommand = "s\n" + target + "\nfield10\ni123\ne\n"; try { command.execute("f", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); assertEquals(((ExampleClass) gateway.getObject(target)).field10, 123); } ca...
public static Index simple(String name) { return new Index(name, false); }
@Test public void getJoinField_throws_ISE_on_simple_index() { Index underTest = Index.simple("foo"); assertThatThrownBy(underTest::getJoinField) .isInstanceOf(IllegalStateException.class) .hasMessage("Only index accepting relations has a join field"); }
public static void renameTo(File src, File dst) throws IOException { if (!nativeLoaded) { if (!src.renameTo(dst)) { throw new IOException("renameTo(src=" + src + ", dst=" + dst + ") failed."); } } else { renameTo0(src.getAbsolutePath(), dst.getAbsolutePath()); } }
@Test (timeout = 30000) public void testRenameTo() throws Exception { final File TEST_DIR = GenericTestUtils.getTestDir("renameTest") ; assumeTrue(TEST_DIR.mkdirs()); File nonExistentFile = new File(TEST_DIR, "nonexistent"); File targetFile = new File(TEST_DIR, "target"); // Test attempting to ren...
@Override public void cancel(InterpreterContext context) throws InterpreterException { String shinyApp = context.getStringLocalProperty("app", DEFAULT_APP_NAME); IRInterpreter irInterpreter = getIRInterpreter(shinyApp); irInterpreter.cancel(context); }
@Test void testInvalidShinyApp() throws IOException, InterpreterException, InterruptedException, UnirestException { InterpreterContext context = getInterpreterContext(); context.getLocalProperties().put("type", "ui"); InterpreterResult result = interpreter.interpret(IOUtils.toString(...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { String[] lines = splitAndRemoveEmpty(st, "\n"); return interpret(lines, context); }
@Test void lsTest() throws IOException, AlluxioException { URIStatus[] files = new URIStatus[3]; FileSystemTestUtils.createByteFile(fs, "/testRoot/testFileA", WritePType.MUST_CACHE, 10, 10); FileSystemTestUtils.createByteFile(fs, "/testRoot/testDir/testFileB", WritePType.MUST_CACH...
protected void processFileContents(List<String> fileLines, String filePath, Engine engine) throws AnalysisException { fileLines.stream() .map(fileLine -> fileLine.split("(,|=>)")) .map(requires -> { //LOGGER.debug("perl scanning file:" + fileLine); ...
@Test public void testProcessFileContents() throws AnalysisException { Dependency d = new Dependency(); List<String> dependencyLines = Arrays.asList(new String[]{ "requires 'Plack', '1.0'", "requires 'JSON', '>= 2.00, < 2.80'", "requires 'Mojolicious::Plugin::ZAPI...
public static String getShortName(String destinationName) { if (destinationName == null) { throw new IllegalArgumentException("destinationName is null"); } if (destinationName.startsWith("queue:")) { return destinationName.substring(6); } else if (destinationName....
@Test public void testGetShortNameNullDestinationName() { assertThrows(IllegalArgumentException.class, () -> DestinationNameParser.getShortName(null)); }
@Override public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) { if(StringUtils.containsAny(remote.getName(), '*')) { // Treat asterisk as wildcard return Collections.singleton(new TransferItem(remote.getParent())); } ...
@Test public void testFindDirectory() throws Exception { final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace://cdn.cyberduck.ch/remote"}); assertTrue(new DeletePathFinder().find(inpu...
public static IcebergDecimalObjectInspector get(int precision, int scale) { Preconditions.checkArgument(scale <= precision); Preconditions.checkArgument(precision <= HiveDecimal.MAX_PRECISION); Preconditions.checkArgument(scale <= HiveDecimal.MAX_SCALE); Integer key = precision << 8 | scale; return...
@Test public void testCache() { HiveDecimalObjectInspector oi = IcebergDecimalObjectInspector.get(38, 18); Assert.assertSame(oi, IcebergDecimalObjectInspector.get(38, 18)); Assert.assertNotSame(oi, IcebergDecimalObjectInspector.get(28, 18)); Assert.assertNotSame(oi, IcebergDecimalObjectInspector.get(...
public GroupInformation createGroup(DbSession dbSession, String name, @Nullable String description) { validateGroupName(name); checkNameDoesNotExist(dbSession, name); GroupDto group = new GroupDto() .setUuid(uuidFactory.create()) .setName(name) .setDescription(description); return gro...
@Test @UseDataProvider("invalidGroupNames") public void createGroup_whenGroupNameIsInvalid_throws(String groupName, String errorMessage) { mockDefaultGroup(); assertThatExceptionOfType(BadRequestException.class) .isThrownBy(() -> groupService.createGroup(dbSession, groupName, "Description")) .w...
@Override public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) { checkPermission(FLOWRULE_WRITE); if (forwardingObjective.nextId() == null || flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null || !queueFwdObjective(deviceI...
@Test public void forwardingObjective() { TrafficSelector selector = DefaultTrafficSelector.emptySelector(); TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment(); ForwardingObjective forward = DefaultForwardingObjective.builder() .from...
@Override public UnitExtension getUnitExtension(String extensionName) { if (extensionName.equals("SoldierExtension")) { return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this)); } return super.getUnitExtension(extensionName); }
@Test void getUnitExtension() { final var unit = new SoldierUnit("SoldierUnitName"); assertNotNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("CommanderExtension")); }
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { List<String> basePath = getPathComponents(canonicalBaseFile); List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); //if the roots aren't the same (i.e. different drives on a ...
@Test public void pathUtilTest1() { File[] roots = File.listRoots(); if (roots.length > 1) { File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); File relativePath = new File(roots[1] + "some" + File.separatorChar + "dir...
public <T> T getFieldAs(final Class<T> T, final String key) throws ClassCastException { return T.cast(getField(key)); }
@Test public void testGetFieldAs() throws Exception { message.addField("fields", Lists.newArrayList("hello")); assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields")); }
public void addStripAction(@NonNull StripActionProvider provider, boolean highPriority) { for (var stripActionView : mStripActionViews) { if (stripActionView.getTag(PROVIDER_TAG_ID) == provider) { return; } } var actionView = provider.inflateActionView(this); if (actionView.getParen...
@Test public void testHighBothPriority() { View view = new View(mUnderTest.getContext()); View view2 = new View(mUnderTest.getContext()); KeyboardViewContainerView.StripActionProvider provider = Mockito.mock(KeyboardViewContainerView.StripActionProvider.class); Mockito.doReturn(view).when(prov...
public static JaasContext loadServerContext(ListenerName listenerName, String mechanism, Map<String, ?> configs) { if (listenerName == null) throw new IllegalArgumentException("listenerName should not be null for SERVER"); if (mechanism == null) throw new IllegalArgumentException...
@Test public void testLoadForServerWithWrongListenerName() throws IOException { writeConfiguration("Server", "test.LoginModule required;"); assertThrows(IllegalArgumentException.class, () -> JaasContext.loadServerContext(new ListenerName("plaintext"), "SOME-MECHANISM", Collections.em...
public final int getEventLen() { return eventLen; }
@Test public void getEventLenOutputZero() { // Arrange final LogHeader objectUnderTest = new LogHeader(0); // Act final int actual = objectUnderTest.getEventLen(); // Assert result Assert.assertEquals(0, actual); }
public static URI buildExternalUri(@NotNull MultivaluedMap<String, String> httpHeaders, @NotNull URI defaultUri) { Optional<URI> externalUri = Optional.empty(); final List<String> headers = httpHeaders.get(HttpConfiguration.OVERRIDE_HEADER); if (headers != null && !headers.isEmpty()) { ...
@Test public void buildExternalUriReturnsDefaultUriIfHeaderIsEmpty() throws Exception { final MultivaluedMap<String, String> httpHeaders = new MultivaluedHashMap<>(); httpHeaders.putSingle(HttpConfiguration.OVERRIDE_HEADER, ""); final URI externalUri = URI.create("http://graylog.example.com/...
public static SimpleTransform exp() { return new SimpleTransform(Operation.exp); }
@Test public void testExp() { TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.exp()),new HashMap<>()); testSimple(t,Math::exp); }
public boolean isAllBindingTables(final Collection<String> logicTableNames) { if (logicTableNames.isEmpty()) { return false; } Optional<BindingTableRule> bindingTableRule = findBindingTableRule(logicTableNames); if (!bindingTableRule.isPresent()) { return false; ...
@Test void assertIsAllBindingTableWithoutJoinQuery() { SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class); when(sqlStatementContext.isContainsJoinQuery()).thenReturn(false); assertTrue( createMaximumShardingRule().isAllBindingTables(mock(ShardingS...
public Optional<String> getType(Set<String> streamIds, String field) { final Map<String, Set<String>> allFieldTypes = this.get(streamIds); final Set<String> fieldTypes = allFieldTypes.get(field); return typeFromFieldType(fieldTypes); }
@Test void returnsEmptyOptionalIfFieldTypesAreEmpty() { final Pair<IndexFieldTypesService, StreamService> services = mockServices(); final FieldTypesLookup lookup = new FieldTypesLookup(services.getLeft(), services.getRight()); final Optional<String> result = lookup.getType(Collections.singl...
static Serializer createSerializer(Fury fury, Class<?> cls) { for (Tuple2<Class<?>, Function> factory : synchronizedFactories()) { if (factory.f0 == cls) { return createSerializer(fury, factory); } } throw new IllegalArgumentException("Unsupported type " + cls); }
@Test public void testWrite() throws Exception { Fury fury = Fury.builder().withLanguage(Language.JAVA).requireClassRegistration(false).build(); MemoryBuffer buffer = MemoryUtils.buffer(32); Object[] values = new Object[] { Collections.synchronizedCollection(Collections.singletonList("ab...
@Override public WebSocketServerExtension handshakeExtension(WebSocketExtensionData extensionData) { if (!X_WEBKIT_DEFLATE_FRAME_EXTENSION.equals(extensionData.name()) && !DEFLATE_FRAME_EXTENSION.equals(extensionData.name())) { return null; } if (extensionData.parame...
@Test public void testWebkitHandshake() { // initialize DeflateFrameServerExtensionHandshaker handshaker = new DeflateFrameServerExtensionHandshaker(); // execute WebSocketServerExtension extension = handshaker.handshakeExtension( new WebSocketExtensi...
public void performAction(Command s, int actionIndex) { actions.get(actionIndex).updateModel(s); }
@Test void testPerformAction() { final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); Action action = new Action(model); GiantView giantView = new GiantView(); Dispatcher dispatcher = new Dispatcher(giantView); assertEquals(Nourishment.SATURATED...
public static Extension findExtensionAnnotation(Class<?> clazz) { if (clazz.isAnnotationPresent(Extension.class)) { return clazz.getAnnotation(Extension.class); } // search recursively through all annotations for (Annotation annotation : clazz.getAnnotations()) { ...
@Test public void findExtensionAnnotationThatMissing() { List<JavaFileObject> generatedFiles = JavaSources.compileAll(JavaSources.Greeting, ExtensionAnnotationProcessorTest.SpinnakerExtension_NoExtension, ExtensionAnnotationProcessorTest.WhazzupGreeting_SpinnakerExtension); a...
public DropTypeCommand create(final DropType statement) { final String typeName = statement.getTypeName(); final boolean ifExists = statement.getIfExists(); if (!ifExists && !metaStore.resolveType(typeName).isPresent()) { throw new KsqlException("Type " + typeName + " does not exist."); } re...
@Test public void shouldCreateDropType() { // Given: final DropType dropType = new DropType(Optional.empty(), EXISTING_TYPE, false); // When: final DropTypeCommand cmd = factory.create(dropType); // Then: assertThat(cmd.getTypeName(), equalTo(EXISTING_TYPE)); }
public static Object eval(String expression, Map<String, Object> context) { return eval(expression, context, ListUtil.empty()); }
@Test public void spELTest(){ final ExpressionEngine engine = new SpELEngine(); final Dict dict = Dict.create() .set("a", 100.3) .set("b", 45) .set("c", -199.100); final Object eval = engine.eval("#a-(#b-#c)", dict, null); assertEquals(-143.8, (double)eval, 0); }
protected boolean inList(String includeMethods, String excludeMethods, String methodName) { //判断是否在白名单中 if (!StringUtils.ALL.equals(includeMethods)) { if (!inMethodConfigs(includeMethods, methodName)) { return false; } } //判断是否在黑白单中 if (inM...
@Test public void PrefixIncludeListTest() { ProviderConfig providerConfig = new ProviderConfig(); DefaultProviderBootstrap defaultProviderBootstra = new DefaultProviderBootstrap(providerConfig); boolean result = defaultProviderBootstra.inList("hello1", "hello1", "hello"); Assert.ass...
public static JsonElement parseString(String json) throws JsonSyntaxException { return parseReader(new StringReader(json)); }
@Test public void testParseString() { String json = "{a:10,b:'c'}"; JsonElement e = JsonParser.parseString(json); assertThat(e.isJsonObject()).isTrue(); assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10); assertThat(e.getAsJsonObject().get("b").getAsString()).isEqualTo("c"); }
@PublicAPI(usage = ACCESS) public static ArchRule testClassesShouldResideInTheSamePackageAsImplementation() { return testClassesShouldResideInTheSamePackageAsImplementation("Test"); }
@Test public void should_pass_when_test_class_is_missing_and_only_implementation_provided() { assertThatRule(testClassesShouldResideInTheSamePackageAsImplementation()) .checking(new ClassFileImporter().importPackagesOf(ImplementationClassWithoutTestClass.class)) .hasNoViolati...
@Override public InterpreterResult interpret(final String st, final InterpreterContext context) throws InterpreterException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("st:\n{}", st); } final FormType form = getFormType(); RemoteInterpreterProcess interpreterProcess = null; try { ...
@Test void testFailToLaunchInterpreterProcess_InvalidRunner() { try { System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_REMOTE_RUNNER.getVarName(), "invalid_runner"); final Interpreter interpreter1 = interpreterSetting.getInterpreter("user1", note1Id, "sleep"); final Interpr...
public static void executeWithRetry(RetryFunction function) throws Exception { executeWithRetry(maxAttempts, minDelay, function); }
@Test public void retryFunctionThatWillFail() throws Exception { exceptionRule.expect(SQLException.class); exceptionRule.expectMessage("Problem with connection"); executeWithRetry(IOITHelperTest::failingFunction); assertEquals(3, listOfExceptionsThrown.size()); }
@Override public Serde<List<?>> getSerde( final PersistenceSchema schema, final Map<String, String> formatProps, final KsqlConfig config, final Supplier<SchemaRegistryClient> srFactory, final boolean isKey ) { SerdeUtils.throwOnUnsupportedFeatures(schema.features(), supportedFeatur...
@Test public void shouldThrowOnSerializationIfStructColumnValueDoesNotMatchSchema() { // Given: final SimpleColumn singleColumn = createColumn( "bob", SqlTypes.struct() .field("vic", SqlTypes.STRING) .build() ); when(persistenceSchema.columns()).thenReturn(Immut...
public static boolean equalsIgnoreCase(String a, String b) { if (a == null) { return b == null; } return a.equalsIgnoreCase(b); }
@Test void testEqualsIgnoreCase() { Assertions.assertTrue(StringUtils.equalsIgnoreCase("a", "a")); Assertions.assertTrue(StringUtils.equalsIgnoreCase("a", "A")); Assertions.assertTrue(StringUtils.equalsIgnoreCase("A", "a")); Assertions.assertFalse(StringUtils.equalsIgnoreCase("1", "2...
public static LeaderInformationRegister merge( @Nullable LeaderInformationRegister leaderInformationRegister, String componentId, LeaderInformation leaderInformation) { final Map<String, LeaderInformation> existingLeaderInformation = new HashMap<>( ...
@Test void testMerge() { final String componentId = "component-id"; final LeaderInformation leaderInformation = LeaderInformation.known(UUID.randomUUID(), "address"); final String newComponentId = "new-component-id"; final LeaderInformation newLeaderInformation = ...
public static Collection<File> getFileResourcesFromDirectory(File directory, Pattern pattern) { if (directory == null || directory.listFiles() == null) { return Collections.emptySet(); } return Arrays.stream(Objects.requireNonNull(directory.listFiles())) .flatMap( ...
@Test public void getResourcesFromDirectoryExisting() { File directory = new File("." + File.separator + "target" + File.separator + "test-classes"); Pattern pattern = Pattern.compile(".*txt"); final Collection<File> retrieved = getFileResourcesFromDirectory(directory, pattern); comm...
public static InternalRequestSignature fromHeaders(Crypto crypto, byte[] requestBody, HttpHeaders headers) { if (headers == null) { return null; } String signatureAlgorithm = headers.getHeaderString(SIGNATURE_ALGORITHM_HEADER); String encodedSignature = headers.getHeaderStri...
@Test public void fromHeadersShouldReturnNullIfSignatureHeaderMissing() { assertNull(InternalRequestSignature.fromHeaders(crypto, REQUEST_BODY, internalRequestHeaders(null, SIGNATURE_ALGORITHM))); }
public void inject(Inspector inspector, Inserter inserter) { if (inspector.valid()) { injectValue(inserter, inspector, null); } }
@Test public void injectIntoSlime() { assertTrue(f1.empty.get().valid()); // explicit nix inject(f1.empty.get(), new SlimeInserter(f2.slime1)); inject(f1.nixValue.get(), new SlimeInserter(f2.slime2)); inject(f1.boolValue.get(), new SlimeInserter(f2.slime3)); inject(f1.longVa...
static Properties adminClientConfiguration(String bootstrapHostnames, PemTrustSet kafkaCaTrustSet, PemAuthIdentity authIdentity, Properties config) { if (config == null) { throw new InvalidConfigurationException("The config parameter should not be null"); } config.setProperty(Adm...
@Test public void testPlainConnection() { Properties config = DefaultAdminClientProvider.adminClientConfiguration("my-kafka:9092", null, null, new Properties()); assertThat(config.size(), is(5)); assertDefaultConfigs(config); }
@Override public void close() throws IOException { InputFileBlockHolder.unset(); // close the current iterator this.currentIterator.close(); // exhaust the task iterator while (tasks.hasNext()) { tasks.next(); } }
@Test public void testClosureWithoutAnyRead() throws IOException { Integer totalTasks = 10; Integer recordPerTask = 10; List<FileScanTask> tasks = createFileScanTasks(totalTasks, recordPerTask); ClosureTrackingReader reader = new ClosureTrackingReader(table, tasks); reader.close(); tasks.fo...
public static void checkDrivingLicenceMrz(String mrz) { if (mrz.charAt(0) != 'D') { throw new VerificationException("MRZ should start with D"); } if (mrz.charAt(1) != '1') { throw new VerificationException("Only BAP configuration is supported (1)"); } if (...
@Test public void checkDrivingLicenceMrzCheckFirstLetterWrong() { assertThrows(VerificationException.class, () -> { MrzUtils.checkDrivingLicenceMrz("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"); }); }
@Override public void onDraw(Canvas canvas) { final boolean keyboardChanged = mKeyboardChanged; super.onDraw(canvas); // switching animation if (mAnimationLevel != AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) { startAnimation(mInAnimation); mInAnimation = null; } ...
@Test public void testExtraDrawMultiple() { ExtraDraw mockDraw1 = Mockito.mock(ExtraDraw.class); ExtraDraw mockDraw2 = Mockito.mock(ExtraDraw.class); Mockito.doReturn(true).when(mockDraw1).onDraw(any(), any(), same(mViewUnderTest)); Mockito.doReturn(true).when(mockDraw2).onDraw(any(), any(), same(mVie...
@Override public Validator getValidator(final URL url) { return new ApacheDubboClientValidator(url); }
@Test public void testGetValidator() { String mockServiceUrl = "mock://localhost:28000/org.apache.shenyu.client.apache.dubbo.validation.mock.MockValidatorTarget"; final URL url = URL.valueOf(mockServiceUrl); apacheDubboClientValidationUnderTest.getValidator(url); }
List<Condition> run(boolean useKRaft) { List<Condition> warnings = new ArrayList<>(); checkKafkaReplicationConfig(warnings); checkKafkaBrokersStorage(warnings); if (useKRaft) { // Additional checks done for KRaft clusters checkKRaftControllerStorage(warnings);...
@Test public void checkKafkaJbodEphemeralStorageSingleController() { KafkaNodePool singleNode = new KafkaNodePoolBuilder(CONTROLLERS) .editSpec() .withReplicas(1) .withStorage( new JbodStorageBuilder().withVolumes( ...
public static List<Event> computeEventDiff(final Params params) { final List<Event> events = new ArrayList<>(); emitPerNodeDiffEvents(createBaselineParams(params), events); emitWholeClusterDiffEvent(createBaselineParams(params), events); emitDerivedBucketSpaceStatesDiffEvents(params, ev...
@Test void storage_node_maintenance_grace_period_event_only_emitted_on_maintenance_to_down_edge() { final EventFixture fixture = EventFixture.createForNodes(3) .clusterStateBefore("distributor:3 storage:3 .0.s:u") .clusterStateAfter("distributor:3 storage:3 .0.s:d") ...
protected boolean isVfsPath( String filePath ) { boolean ret = false; try { VFSFileProvider vfsFileProvider = (VFSFileProvider) providerService.get( VFSFileProvider.TYPE ); if ( vfsFileProvider == null ) { return false; } return vfsFileProvider.isSupported( filePath ); } catc...
@Test public void testIsVfsPath_NotSupported() throws Exception { // SETUP String vfsPath = "pvfs://someConnection/someFilePath"; ProviderService mockProviderService = mock( ProviderService.class ); VFSFileProvider mockVFSFileProvider = mock( VFSFileProvider.class ); when( mockProviderService.get(...
public Map<String, List<PartitionInfo>> getAllTopicMetadata(Timer timer) { MetadataRequest.Builder request = MetadataRequest.Builder.allTopics(); return getTopicMetadata(request, timer); }
@Test public void testGetAllTopicsUnauthorized() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(newMetadataResponse(Errors.TOPIC_AUTHORIZATION_FAILED)); try { topicMetadataFetcher.getAllTopicMetadata(time.timer(10L)); fail(); ...
public static DataflowRunner fromOptions(PipelineOptions options) { DataflowPipelineOptions dataflowOptions = PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options); ArrayList<String> missing = new ArrayList<>(); if (dataflowOptions.getAppName() == null) { missing.add("appN...
@Test public void testRegionOptionalForNonServiceRunner() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setRegion(null); options.setDataflowEndpoint("http://localhost:20281"); DataflowRunner.fromOptions(options); }
public static void removeUnavailableStepsFromMapping( Map<TargetStepAttribute, SourceStepField> targetMap, Set<SourceStepField> unavailableSourceSteps, Set<TargetStepAttribute> unavailableTargetSteps ) { Iterator<Entry<TargetStepAttribute, SourceStepField>> ta...
@Test public void removeUnavailableStepsFromMapping_unavailable_target_step() { TargetStepAttribute unavailableTargetStep = new TargetStepAttribute( UNAVAILABLE_STEP, TEST_ATTR_VALUE, false ); SourceStepField unavailableSourceStep = new SourceStepField( UNAVAILABLE_STEP, TEST_FIELD ); Map<TargetStepAttrib...
@ExecuteOn(TaskExecutors.IO) @Post(uri = "executions/latest/group-by-flow") @Operation(tags = {"Stats"}, summary = "Get latest execution by flows") public List<Execution> lastExecutions( @Parameter(description = "A list of flows filter") @Body @Valid LastExecutionsRequest lastExecutionsRequest )...
@Test void lastExecutions() { var dailyStatistics = client.toBlocking().retrieve( HttpRequest .POST("/api/v1/stats/executions/latest/group-by-flow", new StatsController.LastExecutionsRequest(List.of(ExecutionRepositoryInterface.FlowFilter.builder().namespace("io.kestra.test").id(...
@Override public String getSchema() { return dialectDatabaseMetaData.getSchema(connection); }
@Test void assertGetSchemaReturnNullWhenThrowsSQLException() throws SQLException { when(connection.getSchema()).thenThrow(SQLException.class); MetaDataLoaderConnection connection = new MetaDataLoaderConnection(databaseType, this.connection); assertNull(connection.getSchema()); }
long getNodeResultLimit(int ownedPartitions) { return isQueryResultLimitEnabled ? (long) ceil(resultLimitPerPartition * ownedPartitions) : Long.MAX_VALUE; }
@Test public void testNodeResultLimitMinResultLimit() { initMocksWithConfiguration(QueryResultSizeLimiter.MINIMUM_MAX_RESULT_LIMIT, 3); long nodeResultLimit1 = limiter.getNodeResultLimit(1); initMocksWithConfiguration(QueryResultSizeLimiter.MINIMUM_MAX_RESULT_LIMIT / 2, 3); long nod...
@Override public V fetch(final K key, final long time) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (final ReadOnlyWindowStore<K, V> windowStore : stores) { try { ...
@Test public void shouldFetchKeyRangeAcrossStores() { final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE); stubProviderTwo.addStore(storeName, secondUnderlying); underlyingWindowStore.put("a", "a", 0L); secondUnderlying.put("b",...
@VisibleForTesting static void validatePartitionStatistics(SchemaTableName table, Map<String, PartitionStatistics> partitionStatistics) { partitionStatistics.forEach((partition, statistics) -> { HiveBasicStatistics basicStatistics = statistics.getBasicStatistics(); OptionalLong r...
@Test public void testValidatePartitionStatistics() { assertInvalidStatistics( PartitionStatistics.builder() .setBasicStatistics(new HiveBasicStatistics(-1, 0, 0, 0)) .build(), invalidPartitionStatistics("fileCount must be g...