focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Duration parse(final String text) { try { final String[] parts = text.split("\\s"); if (parts.length != 2) { throw new IllegalArgumentException("Expected 2 tokens, got: " + parts.length); } final long size = parseNumeric(parts[0]); return buildDuration(size, part...
@Test public void shouldIncludeValidTimeUnitsInExceptionMessage() { // Then: // When: final Exception e = assertThrows( IllegalArgumentException.class, () -> parse("10 Bananas") ); // Then: assertThat(e.getMessage(), containsString("Supported time units are: " + "NANOS...
public static Class<?> forName(String name) throws ClassNotFoundException { return forName(name, getClassLoader()); }
@Test void testForName1() throws Exception { assertThat(ClassUtils.forName(ClassUtilsTest.class.getName()) == ClassUtilsTest.class, is(true)); }
@Override public N getSchedulerNode(NodeId nodeId) { return nodeTracker.getNode(nodeId); }
@Test(timeout = 30000L) public void testNodeRemovedWithAllocationTags() throws Exception { // Currently only can be tested against capacity scheduler. if (getSchedulerType().equals(SchedulerType.CAPACITY)) { final String testTag1 = "some-tag"; YarnConfiguration conf = getConf(); conf.set(Yar...
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test public void shouldRemoveBrokenNestedRefsKeepComposedSchemas() throws IOException { final OpenAPI openAPI = getOpenAPI31(RESOURCE_PATH_COMPOSED_SCHEMA); final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter(); final OpenAPI filtered = new SpecFilter...
@Override public HashSlotCursor12byteKey cursor() { return new CursorIntKey2(); }
@Test(expected = AssertionError.class) public void testCursor_advance_whenDisposed() { HashSlotCursor12byteKey cursor = hsa.cursor(); hsa.dispose(); cursor.advance(); }
public static SmartFilterTestExecutionResultDTO execSmartFilterTest(SmartFilterTestExecutionDTO execData) { Predicate<TopicMessageDTO> predicate; try { predicate = MessageFilters.celScriptFilter(execData.getFilterCode()); } catch (Exception e) { log.info("Smart filter '{}' compilation error", ex...
@Test void execSmartFilterTestReturnsExecutionResult() { var params = new SmartFilterTestExecutionDTO() .filterCode("has(record.key) && has(record.value) && record.headers.size() != 0 " + "&& has(record.timestampMs) && has(record.offset)") .key("1234") .value("{ \"some\" : \"va...
public long getAndSet(long newValue) { return getAndSetVal(newValue); }
@Test public void testGetAndSet() { PaddedAtomicLong counter = new PaddedAtomicLong(1); long result = counter.getAndSet(2); assertEquals(1, result); assertEquals(2, counter.get()); }
@Override public KubevirtIpPool ipPool() { return ipPool; }
@Test public void testIpAllocationAndRelease() throws Exception { KubevirtIpPool ipPool1 = network1.ipPool(); IpAddress ip = ipPool1.allocateIp(); assertEquals(100, ipPool1.availableIps().size()); assertEquals(1, ipPool1.allocatedIps().size()); assertEquals(IpAddress.valueOf(...
static void writeResponse(Configuration conf, Writer out, String format, String propertyName) throws IOException, IllegalArgumentException, BadFormatException { if (FORMAT_JSON.equals(format)) { Configuration.dumpConfiguration(conf, propertyName, out); } else if (FORMAT_XML.equals(format))...
@Test @SuppressWarnings("unchecked") public void testWriteJson() throws Exception { StringWriter sw = new StringWriter(); ConfServlet.writeResponse(getTestConf(), sw, "json"); String json = sw.toString(); boolean foundSetting = false; Object parsed = JSON.parse(json); Object[] properties = (...
protected void replaceJettyXmlIfItBelongsToADifferentVersion(File jettyConfig) throws IOException { if (Files.readString(jettyConfig.toPath(), UTF_8).contains(JETTY_CONFIG_VERSION)) return; replaceFileWithPackagedOne(jettyConfig); }
@Test public void shouldReplaceJettyXmlIfItDoesNotContainCorrespondingJettyVersionNumber(@TempDir Path temporaryFolder) throws IOException { Path jettyXml = Files.createFile(temporaryFolder.resolve("jetty.xml")); when(systemEnvironment.getJettyConfigFile()).thenReturn(jettyXml.toFile()); St...
protected String decideSource(MappedMessage cef, RawMessage raw) { // Try getting the host name from the CEF extension "deviceAddress"/"dvc" final Map<String, Object> fields = cef.mappedExtensions(); if (fields != null && !fields.isEmpty()) { final String deviceAddress = (String) fie...
@Test public void decideSourceWithFullDeviceAddressReturnsExtensionValue() throws Exception { final MappedMessage cefMessage = mock(MappedMessage.class); when(cefMessage.mappedExtensions()).thenReturn(Collections.singletonMap("deviceAddress", "128.66.23.42")); final RawMessage rawMessage = ...
@Override public boolean isProjectVisibilitySynchronizationActivated() { return findManagedProjectService() .map(ManagedProjectService::isProjectVisibilitySynchronizationActivated) .orElse(false); }
@Test public void isProjectVisibilitySynchronizationActivated_whenManagedInstanceServices_shouldDelegatesToRightService() { DelegatingManagedServices managedInstanceService = new DelegatingManagedServices(Set.of(new NeverManagedInstanceService(), new AlwaysManagedInstanceService())); assertThat(managedInstan...
public List<B2UploadPartResponse> list(final String fileid) throws BackgroundException { if(log.isInfoEnabled()) { log.info(String.format("List completed parts of file %s", fileid)); } // This operation lists the parts that have been uploaded for a specific multipart upload. ...
@Test public void testList() throws Exception { final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final B2StartLargeFileResponse startResponse = sess...
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { SQLStatement dalStatement = sqlStatementContext.getSq...
@Test void assertMergeForShowTableStatusStatement() throws SQLException { DALStatement dalStatement = new MySQLShowTableStatusStatement(); SQLStatementContext sqlStatementContext = mockSQLStatementContext(dalStatement); ShardingDALResultMerger resultMerger = new ShardingDALResultMerger(Defau...
@Override public void close() { if (!isVersionCommitted) { job.setVersion(initialJobVersion); } }
@Test void testJobVersionerOnRollbackVersionIsRestored() { // GIVEN Job job = aScheduledJob().withVersion(5).build(); // WHEN JobVersioner jobVersioner = new JobVersioner(job); // THEN assertThat(job).hasVersion(6); // WHEN jobVersioner.close(); ...
public static void main(String[] args) throws Exception { DateFormat dateFormat = new SimpleDateFormat( FixedDateFormat.FixedFormat.ISO8601_OFFSET_DATE_TIME_HHMM.getPattern()); Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> { System.out.println(String.format("%s...
@Test public void testMainGenerateDocs() throws Exception { PrintStream oldStream = System.out; try { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); Class argumentsClass = Class.forName("org.apache.pulsar...
public void installIntents(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) { // If no any Intents to be uninstalled or installed, ignore it. if (!toUninstall.isPresent() && !toInstall.isPresent()) { return; } // Classify installable Intents to different ins...
@Test public void testInstallNothing() { installCoordinator.installIntents(Optional.empty(), Optional.empty()); assertNull(intentStore.newData); }
static void runHook() { for (String filename : FILES) { new File(filename).delete(); } }
@Test public void testSimulateTriggerDeleteFileOnExitHook() { // simulate app exit DeleteFileOnExitHook.runHook(); File[] files = new File(HOOK_TEST_TMP).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return...
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testIsHeldByCurrentThread() { RLock lock = redisson.getLock("lock"); Assertions.assertFalse(lock.isHeldByCurrentThread()); lock.lock(); Assertions.assertTrue(lock.isHeldByCurrentThread()); lock.unlock(); Assertions.assertFalse(lock.isHeldByCurrentThr...
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } checkNoComponentAnnotations(stepClass); if (hasCucumberContextConfiguration(stepClass)) { checkOnlyOneClassHasCucumberContextConfiguration(step...
@Test void shouldBeStoppableWhenFacedWithInvalidConfiguration() { final ObjectFactory factory = new SpringFactory(); factory.addClass(WithEmptySpringAnnotations.class); IllegalStateException exception = assertThrows(IllegalStateException.class, factory::start); assertThat(exception....
@Override public int getPartitionId(Object object) { return client.getClientPartitionService().getPartitionId(object); }
@Test public void testPartitionId() { int partitionId = context.getPartitionId("myKey"); assertTrue(partitionId >= 0); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void sub1() { String inputExpression = "(y - 5) ** 3"; BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) ); assertThat( infix).isInstanceOf(InfixOpNode.class); assertThat( infix.getResultType()).isEqualTo(BuiltInType.NUMBER); assertThat( in...
@Override public boolean isGroupManaged(DbSession dbSession, String groupUuid) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.isGroupManaged(dbSession, groupUuid)) .orElse(false); }
@Test public void isGroupManaged_delegatesToRightService_andPropagateAnswer() { DelegatingManagedServices managedInstanceService = new DelegatingManagedServices(Set.of(new NeverManagedInstanceService(), new AlwaysManagedInstanceService())); assertThat(managedInstanceService.isGroupManaged(dbSession, "whateve...
@Experimental public static Configuration forReporter(Configuration configuration, String reporterName) { return new DelegatingConfiguration( configuration, ConfigConstants.METRICS_REPORTER_PREFIX + reporterName + "."); }
@Test void testForReporterRead() { Configuration configuration = new Configuration(); configuration.set(FULL_OPTION, "value"); assertThat(MetricOptions.forReporter(configuration, "my_reporter").get(SUB_OPTION)) .isEqualTo("value"); }
public static <T> Iterator<T> prepend(T prepend, @Nonnull Iterator<? extends T> iterator) { checkNotNull(iterator, "iterator cannot be null."); return new PrependIterator<>(prepend, iterator); }
@Test public void prependNullToEmptyIterator() { var actual = IterableUtil.prepend(null, Collections.emptyIterator()); assertIteratorsEquals(Collections.emptyList(), actual); }
public int add(Object o) { HollowTypeMapper typeMapper = getTypeMapper(o.getClass(), null, null); return typeMapper.write(o); }
@Test public void testNullElements() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); // Lists cannot contain null elements try { mapper.add(new TypeWithList("a", null, "c")); Assert.fail("NullPointerException not thrown from List containing nu...
@Deprecated public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) { return Task.callable(name, () -> callable.call()); }
@Test public void testDelayTaskFailed() { IllegalArgumentException exception = new IllegalArgumentException("Oops!"); final Task<Integer> task = Task.callable(() -> { throw exception; }); final Task<Integer> taskWithDelay = task.withDelay(200, TimeUnit.MILLISECONDS); IllegalArgumentExceptio...
public TriRpcStatus appendDescription(String description) { if (this.description == null) { return withDescription(description); } else { String newDescription = this.description + "\n" + description; return withDescription(newDescription); } }
@Test void appendDescription() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withDesc = origin.appendDescription("desc0"); TriRpcStatus withDesc2 = withDesc.appendDescription("desc1"); Assertions.assertNull(origin.description); Assertions.assertTrue(withDesc2....
@Override public byte[] serializeValue(CoordinatorRecord record) { // Tombstone is represented with a null value. if (record.value() == null) { return null; } else { return MessageUtil.toVersionPrefixedBytes( record.value().version(), r...
@Test public void testSerializeValue() { GroupCoordinatorRecordSerde serializer = new GroupCoordinatorRecordSerde(); CoordinatorRecord record = new CoordinatorRecord( new ApiMessageAndVersion( new ConsumerGroupMetadataKey().setGroupId("group"), (short) 3 ...
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception { return newGetter(object, parent, modifier, method.getReturnType(), method::invoke, (t, et) -> new MethodGetter(parent, method, modifier, t, et)); }
@Test public void newMethodGetter_whenExtractingFromSimpleField_thenReturnFieldContentIsItIs() throws Exception { OuterObject object = new OuterObject("name"); Getter getter = GetterFactory.newMethodGetter(object, null, outerNameMethod, null); String result = (String) getter.getValue(object...
public static <T> RBFNetwork<T> fit(T[] x, double[] y, RBF<T>[] rbf) { return fit(x, y, rbf, false); }
@Test public void test2DPlanes() { System.out.println("2dplanes"); MathEx.setSeed(19650218); // to get repeatable results. RegressionValidations<RBFNetwork<double[]>> result = CrossValidation.regression(10, Planes.x, Planes.y, (xi, yi) -> RBFNetwork.fit(xi, yi, RBF.fit(xi, ...
public synchronized BeamFnStateClient forApiServiceDescriptor( ApiServiceDescriptor apiServiceDescriptor) throws IOException { // We specifically are synchronized so that we only create one GrpcStateClient at a time // preventing a race where multiple GrpcStateClient objects might be constructed at the sa...
@Test // The checker erroneously flags that the CompletableFuture is not being resolved since it is the // result to Executor#submit. @SuppressWarnings("FutureReturnValueIgnored") public void testServerErrorCausesPendingAndFutureCallsToFail() throws Exception { BeamFnStateClient client = clientCache.forApiS...
@NotNull public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) { // 优先从 DB 中获取,因为 code 有且可以使用一次。 // 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次 SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state); i...
@Test public void testAuthSocialUser_exists() { // 准备参数 Integer socialType = SocialTypeEnum.GITEE.getType(); Integer userType = randomEle(SocialTypeEnum.values()).getType(); String code = "tudou"; String state = "yuanma"; // mock 方法 SocialUserDO socialUser = r...
@Override public InterpreterResult interpret(String script, InterpreterContext context) { LOGGER.debug("Run MongoDB script: {}", script); if (StringUtils.isEmpty(script)) { return new InterpreterResult(Code.SUCCESS); } String paragraphId = context.getParagraphId(); // Write script in a tem...
@Test void testSuccess() { final String userScript = "print('hello');"; final InterpreterResult res = interpreter.interpret(userScript, context); assertSame(Code.SUCCESS, res.code(), "Check SUCCESS: " + res.message()); try { out.flush(); } catch (IOException ex) { System.out.println...
protected String getConfig(File configFile) { return ThrowableFunction.execute( configFile, file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); }
@Test void testPublishAndGetConfig() { assertTrue(configuration.publishConfig(KEY, CONTENT)); assertTrue(configuration.publishConfig(KEY, CONTENT)); assertTrue(configuration.publishConfig(KEY, CONTENT)); assertEquals(CONTENT, configuration.getConfig(KEY, DEFAULT_GROUP)); }
public ProviderBuilder networker(String networker) { this.networker = networker; return getThis(); }
@Test void networker() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.networker("networker"); Assertions.assertEquals("networker", builder.build().getNetworker()); }
@Override void toHtml() throws IOException { writeHtmlHeader(); htmlCoreReport.toHtml(); writeHtmlFooter(); }
@Test public void testWithNoDatabase() throws IOException { final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml(null, null); assertNotEmptyAndClear(writer); }
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { return payload.readStringFixByBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); }
@Test void assertReadWithMeta4() { columnDef.setColumnMeta(4); when(payload.readInt4()).thenReturn(Integer.MAX_VALUE); when(payload.readStringFixByBytes(Integer.MAX_VALUE)).thenReturn(new byte[255]); assertThat(new MySQLBlobBinlogProtocolValue().read(columnDef, payload), is(new byte[...
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldCreateCommandForPlannedQueryInDedicatedRuntime() { // Given: givenPlannedQuery(); PersistentQueryMetadataImpl queryMetadata = mock(PersistentQueryMetadataImpl.class); when(executionContext.execute(any(), any(ConfiguredKsqlPlan.class))).thenReturn(result); when(result.getQue...
@Override public Event clone() { final ConvertedMap map = ConvertedMap.newFromMap(Cloner.<Map<String, Object>>deep(data)); map.putInterned(METADATA, Cloner.<Map<String, Object>>deep(metadata)); return new Event(map); }
@Test public void testClone() throws Exception { Map<String, Object> data = new HashMap<>(); List<Object> l = new ArrayList<>(); data.put("array", l); Map<String, Object> m = new HashMap<>(); m.put("foo", "bar"); l.add(m); data.put("foo", 1.0); data....
public static BufferedImage alphaOffset(final Image rawImg, final int offset) { BufferedImage image = toARGB(rawImg); final int numComponents = image.getColorModel().getNumComponents(); final float[] scales = new float[numComponents]; final float[] offsets = new float[numComponents]; Arrays.fill(scales, 1f)...
@Test public void alphaOffset() { // alphaOffset(BufferedImage image, int offset) assertTrue(bufferedImagesEqual(oneByOne(BLACK_TRANSPARENT), ImageUtil.alphaOffset(oneByOne(BLACK_TRANSPARENT), -255))); assertTrue(bufferedImagesEqual(oneByOne(new Color(0, 0, 0, 50)), ImageUtil.alphaOffset(oneByOne(BLACK_TRANSPAR...
public boolean isEmpty() { return branches.isEmpty(); }
@Test public void isEmpty() { assertThat(underTest.isEmpty()).isFalse(); assertThat(new ProjectBranches(Collections.emptyList()).isEmpty()).isTrue(); assertThat(new ProjectBranches(Collections.emptyList()).defaultBranchName()).isEqualTo("main"); }
public static RowCoder of(Schema schema) { return new RowCoder(schema); }
@Test(expected = NonDeterministicException.class) public void testVerifyDeterministic() throws NonDeterministicException { Schema schema = Schema.builder() .addField("f1", FieldType.DOUBLE) .addField("f2", FieldType.FLOAT) .addField("f3", FieldType.INT32) .b...
private List<Object> getTargetInvokersByRequest(String targetName, List<Object> invokers, Object invocation) { Map<String, Object> attachments = parseAttachments(invocation); List<String> requestTags = routerConfig.getRequestTags(); if (CollectionUtils.isEmpty(requestTags)) { return ...
@Test public void testGetTargetInvokersByRequest() { config.setRequestTags(Arrays.asList("foo", "bar", "version")); config.setUseRequestRouter(true); List<Object> invokers = new ArrayList<>(); ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0", Collections.s...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { // set the encoding? try { SyndFeedInput input = new SyndFeedInput(); input.setAllowDoctypes(false); ...
@Test public void testRSSParser() throws Exception { // These RSS files should have basically the same contents, // represented in the various RSS format versions for (String rssFile : new String[]{"/test-documents/rsstest_091.rss", "/test-documents/rsstest_20.rss"}) { ...
public static String underScoreToCamelCase(String key) { if (key.isEmpty()) return key; StringBuilder sb = new StringBuilder(key.length()); for (int i = 0; i < key.length(); i++) { char c = key.charAt(i); if (c == '_') { i++; i...
@Test public void testUnderscoreToCamelCase() { assertEquals("testCase", Helper.underScoreToCamelCase("test_case")); assertEquals("testCaseTBD", Helper.underScoreToCamelCase("test_case_t_b_d")); assertEquals("TestCase_", Helper.underScoreToCamelCase("_test_case_")); }
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test public void isEqualTo_WithoutToleranceParameter_Fail_Shorter() { expectFailureWhenTestingThat(array(2.2f, 3.3f)).isEqualTo(array(2.2f)); }
@Override public PageResult<ApiAccessLogDO> getApiAccessLogPage(ApiAccessLogPageReqVO pageReqVO) { return apiAccessLogMapper.selectPage(pageReqVO); }
@Test public void testGetApiAccessLogPage() { ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> { o.setUserId(2233L); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setApplicationName("yudao-test"); o.setRequestUrl("foo"); o.se...
public boolean deleteReplica(Replica replica) { try (CloseableLock ignored = CloseableLock.lock(this.rwLock.writeLock())) { if (replicas.contains(replica)) { replicas.remove(replica); GlobalStateMgr.getCurrentState().getTabletInvertedIndex().deleteReplica(id, replica....
@Test public void deleteReplicaTest() { // delete replica1 Assert.assertTrue(tablet.deleteReplicaByBackendId(replica1.getBackendId())); Assert.assertNull(tablet.getReplicaById(replica1.getId())); // err: re-delete replica1 Assert.assertFalse(tablet.deleteReplicaByBackendId(r...
public SCMView getSCMView(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_SCM_VIEW, new DefaultPluginInteractionCallback<>() { @Override public SCMView onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { ...
@Test public void shouldTalkToPluginToGetSCMView() throws Exception { SCMView deserializedResponse = new SCMView() { @Override public String displayValue() { return null; } @Override public String template() { retur...
@Override public void registry(ServiceInstance serviceInstance) { DiscoveryManager.INSTANCE.registry(serviceInstance); }
@Test public void registry() { final ServiceInstance serviceInstance = CommonUtils.buildInstance(serviceName, 8989); DiscoveryManager.INSTANCE.registry(serviceInstance); Mockito.verify(zkService34, Mockito.times(1)).registry(serviceInstance); }
@Override public List<String> splitAndEvaluate() { return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : flatten(evaluate(GroovyUtils.split(handlePlaceHolder(inlineExpression)))); }
@Test void assertEvaluateForRange() { List<String> expected = TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", PropertiesBuilder.build( new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, "t_order_${0..2},t_order_item_${0..1}"))).splitAndEvaluate(); ...
static boolean isProcessFile(final String pathName) { return pathName.endsWith("bpmn") || pathName.endsWith("bpmn2") || pathName.endsWith("bpmn-cm"); }
@Test public void testIsProcessFile() { assertThat(KieModuleMetaDataImpl.isProcessFile("abc.bpmn")).isTrue(); assertThat(KieModuleMetaDataImpl.isProcessFile("abc.bpmn2")).isTrue(); assertThat(KieModuleMetaDataImpl.isProcessFile("abc.bpmn-cm")).isTrue(); assertThat(KieModuleMetaDataIm...
public static DirectoryLock lockForDirectory(File dir, ILogger logger) { File lockFile = new File(dir, FILE_NAME); FileChannel channel = openChannel(lockFile); FileLock lock = acquireLock(lockFile, channel); if (logger.isFineEnabled()) { logger.fine("Acquired lock on " + lock...
@Test public void test_lockForDirectory_whenAlreadyLocked() { directoryLock = lockForDirectory(directory, logger); assertThatThrownBy(() -> lockForDirectory(directory, logger)).isInstanceOf(HazelcastException.class); }
public void tick() { // The main loop does two primary things: 1) drive the group membership protocol, responding to rebalance events // as they occur, and 2) handle external requests targeted at the leader. All the "real" work of the herder is // performed in this thread, which keeps synchroniz...
@Test public void testIncrementalCooperativeRebalanceForExistingMember() { connectProtocolVersion = CONNECT_PROTOCOL_V1; // Join group. First rebalance contains revocations because a new member joined. when(member.memberId()).thenReturn("member"); when(member.currentProtocolVersion()...
@Override @Transactional(value="defaultTransactionManager") public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException { if (Strings.isNullOrEmpty(refreshTokenValue)) { // throw an invalid token exception if there's no refresh token val...
@Test public void refreshAccessToken_requestingLessScope() { Set<String> lessScope = newHashSet("openid", "profile"); tokenRequest.setScope(lessScope); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet...
public Predicate<InMemoryFilterable> parse(final List<String> filterExpressions, final List<EntityAttribute> attributes) { if (filterExpressions == null || filterExpressions.isEmpty()) { return Predicates.alwaysTrue(); } final Map<String...
@Test void returnsAlwaysTruePredicateOnNullFilterList() { assertThat(toTest.parse(null, List.of())) .isEqualTo(Predicates.alwaysTrue()); }
static BlockStmt getComplexPartialScoreVariableDeclaration(final String variableName, final ComplexPartialScore complexPartialScore) { final MethodDeclaration methodDeclaration = COMPLEX_PARTIAL_SCORE_TEMPLATE.getMethodsByName(GETKIEPMMLCOMPLEXPARTIALSCORE).get(0).clone(); final BlockStmt complexPartial...
@Test void getComplexPartialScoreVariableDeclaration() throws IOException { final String variableName = "variableName"; Constant constant = new Constant(); constant.setValue(value1); ComplexPartialScore complexPartialScore = new ComplexPartialScore(); complexPartialScore.setE...
@Override public String getTableAlias() { SQLSelectQueryBlock selectQueryBlock = getSelect(); SQLTableSource tableSource = selectQueryBlock.getFrom(); return tableSource.getAlias(); }
@Test public void testGetTableAlias() { //test for no alias String sql = "SELECT * FROM t WITH (UPDLOCK) WHERE id = ?"; SQLStatement ast = getSQLStatement(sql); SqlServerSelectForUpdateRecognizer recognizer = new SqlServerSelectForUpdateRecognizer(sql, ast); Assertions.asser...
public static Date parseHttpDate(CharSequence txt) { return parseHttpDate(txt, 0, txt.length()); }
@Test public void testParseWithFunkyTimezone() { assertEquals(DATE, parseHttpDate("Sun Nov 06 08:49:37 1994 -0000")); }
public Namespace findBranch(String appId, String parentClusterName, String namespaceName) { return namespaceService.findChildNamespace(appId, parentClusterName, namespaceName); }
@Test @Sql(scripts = "/sql/namespace-branch-test.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testFindBranch() { Namespace branch = namespaceBranchService.findBranch(testApp, testCluster, testN...
@Override public DataType getDataType() { return DataType.PREDICATE; }
@Test public void requireThatDataTypeIsPredicate() { assertEquals(DataType.PREDICATE, new PredicateFieldValue().getDataType()); }
@Override public void track(String eventName, JSONObject properties) { }
@Test public void track() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); mSe...
@Override public void close() throws IOException { if (mClosed.getAndSet(true)) { LOG.warn("OBSOutputStream is already closed"); return; } mLocalOutputStream.close(); try { BufferedInputStream in = new BufferedInputStream( new FileInputStream(mFile)); ObjectMetadata o...
@Test @PrepareForTest(OBSOutputStream.class) public void testCloseSuccess() throws Exception { PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(mFile); FileOutputStream outputStream = PowerMockito.mock(FileOutputStream.class); PowerMockito.whenNew(FileOutputStream.class).wi...
public void addReplaceFileId(String partitionPath, String fileId) { if (!partitionToReplaceFileIds.containsKey(partitionPath)) { partitionToReplaceFileIds.put(partitionPath, new ArrayList<>()); } partitionToReplaceFileIds.get(partitionPath).add(fileId); }
@Test public void verifyFieldNamesInReplaceCommitMetadata() throws IOException { List<HoodieWriteStat> fakeHoodieWriteStats = HoodieTestUtils.generateFakeHoodieWriteStat(10); HoodieReplaceCommitMetadata commitMetadata = new HoodieReplaceCommitMetadata(); fakeHoodieWriteStats.forEach(stat -> { commit...
public static Class forName(String className) { return forName(className, true); }
@Test public void forName3() throws Exception { Class clazz = ClassUtils.forName("java.lang.String", Thread.currentThread().getContextClassLoader()); Assert.assertEquals(clazz, String.class); boolean error = false; try { ClassUtils.forName("asdasdasdsad", Thread.currentTh...
public <T> void writeTo(T object, OutputStream entityStream) throws IOException { ObjectWriter writer = objectWriterByClass.get(object.getClass()); if (writer == null) { mapper.writeValue(entityStream, object); } else { writer.writeValue(entityStream, object); } ...
@Test public void testInstanceInfoJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode In...
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_contains_success() { assertThat(array(1.1, TOLERABLE_2POINT2, 3.3)).usingTolerance(DEFAULT_TOLERANCE).contains(2.2); }
public static Pod createPod( String name, String namespace, Labels labels, OwnerReference ownerReference, PodTemplate template, Map<String, String> defaultPodLabels, Map<String, String> podAnnotations, Affinity affinity, ...
@Test public void testCreatePodWithTemplate() { Pod pod = WorkloadUtils.createPod( NAME, NAMESPACE, LABELS, OWNER_REFERENCE, new PodTemplateBuilder() .withNewMetadata() .withLabel...
@Override @SuppressWarnings("deprecation") public HttpRoute determineRoute(HttpHost target, HttpContext context) { if ( ! target.getSchemeName().equals("http") && ! target.getSchemeName().equals("https")) throw new IllegalArgumentException("Scheme must be 'http' or 'https' when using HttpToH...
@Test void verifySchemeIsRewritten() { assertEquals(new HttpRoute(new HttpHost("https", "host", 1)), planner.determineRoute(new HttpHost("http", "host", 1), new HttpClientContext())); }
public long getActualStartTimeMs() { return actualStartTime; }
@Test void initCreate_withStartTime_storesCustomStartTime() throws InterruptedException { long initTime = Instant.now().toEpochMilli(); Thread.sleep(500); AsyncInitializationWrapper init = new AsyncInitializationWrapper(initTime); assertEquals(initTime, init.getActualStartTimeMs());...
public String toLocaleString() { return toLocaleString(localeUTC.getLanguage(), ZoneId.systemDefault().toString()); }
@Test void testToLocaleString() { TbDate d = new TbDate(1693962245000L); // Depends on time zone, so we just check it works; Assertions.assertNotNull(d.toLocaleString()); Assertions.assertNotNull(d.toLocaleString("en-US")); Assertions.assertEquals("9/5/23, 9:04:05 PM", d.to...
public static Range parse(String value, DateFormat dateFormat) { final int index = value.indexOf(CUSTOM_PERIOD_SEPARATOR); if (index == -1) { try { return Period.valueOfIgnoreCase(value).getRange(); } catch (final IllegalArgumentException e) { return Period.JOUR.getRange(); } } // rq: on pourra...
@Test public void testParse() { I18N.bindLocale(Locale.FRENCH); try { final DateFormat dateFormat = I18N.createDateFormat(); assertEquals("parse1", periodRange.getPeriod(), Range.parse(periodRange.getValue(), dateFormat).getPeriod()); assertTrue("parse2", isSameDay(customRange.getStartDate(), Ra...
public List<T> findCycle() { resetState(); for (T vertex : graph.getVertices()) { if (colors.get(vertex) == WHITE) { if (visitDepthFirst(vertex, new ArrayList<>(List.of(vertex)))) { if (cycle == null) throw new IllegalStateException("Null cycle - this shou...
@Test void findCycle_is_idempotent_with_cycle() { var graph = new Graph<Vertices>(); graph.edge(A, A); var cycleFinder = new CycleFinder<>(graph); assertTrue(cycleFinder.findCycle().containsAll(List.of(A, A))); assertTrue(cycleFinder.findCycle().containsAll(List.of(A, A))); ...
Record deserialize(Object data) { return (Record) fieldDeserializer.value(data); }
@Test public void testDeserializeEverySupportedType() { Assume.assumeFalse( "No test yet for Hive3 (Date/Timestamp creation)", HiveVersion.min(HiveVersion.HIVE_3)); Deserializer deserializer = new Deserializer.Builder() .schema(HiveIcebergTestUtils.FULL_SCHEMA) .writerInspector((Struc...
@ApiOperation(value = "Create Or update Tenant (saveTenant)", notes = "Create or update the Tenant. When creating tenant, platform generates Tenant Id as " + UUID_WIKI_LINK + "Default Rule Chain and Device profile are also generated for the new tenants automatically. " + ...
@Test public void testIsolatedQueueDeletion() throws Exception { loginSysAdmin(); TenantProfile tenantProfile = new TenantProfile(); tenantProfile.setName("Test profile"); TenantProfileData tenantProfileData = new TenantProfileData(); tenantProfileData.setConfiguration(new De...
boolean needsMigration() { File mappingFile = UserIdMapper.getConfigFile(usersDirectory); if (mappingFile.exists() && mappingFile.isFile()) { LOGGER.finest("User mapping file already exists. No migration needed."); return false; } File[] userDirectories = listUser...
@Test public void needsMigrationNoUserConfigFiles() throws IOException { UserIdMigrator migrator = createUserIdMigrator(); assertThat(migrator.needsMigration(), is(false)); }
@Override public CompletableFuture<CreateTopicsResponseData> createTopics( ControllerRequestContext context, CreateTopicsRequestData request, Set<String> describable ) { if (request.topics().isEmpty()) { return CompletableFuture.completedFuture(new CreateTopicsResponseData())...
@Test public void testConfigResourceExistenceChecker() throws Throwable { try ( LocalLogManagerTestEnv logEnv = new LocalLogManagerTestEnv.Builder(3). build(); QuorumControllerTestEnv controlEnv = new QuorumControllerTestEnv.Builder(logEnv). setControl...
@Override public T deserialize(final String topic, final byte[] data) { final List<?> values = inner.deserialize(topic, data); if (values == null) { return null; } SerdeUtils.throwOnColumnCountMismatch(numColumns, values.size(), false, topic); return factory.apply(values); }
@Test public void shouldConvertListToRowWhenDeserializing() { // Given: givenInnerDeserializerReturns(ImmutableList.of("world", -10)); // When: final TestListWrapper result = deserializer.deserialize("topicName", SERIALIZED); // Then: assertThat(result.getList(), is(ImmutableList.of("world",...
public static boolean isObjectArray(final Object obj) { return obj instanceof Object[]; }
@SuppressWarnings("ConstantValue") @Test void isObjectArray() { Assertions.assertTrue(DataTypeUtil.isObjectArray(new Object[]{})); Assertions.assertTrue(DataTypeUtil.isObjectArray(new Object[]{new Object()})); Assertions.assertTrue(DataTypeUtil.isObjectArray(new Object[]{new Object(), new Object()})); Assert...
public File saveSecret(String filename) throws IOException { return secretConfig().save(filename); }
@Test public void testSaveSecret() throws IOException { ZCert cert = new ZCert("uYax]JF%mz@r%ERApd<h]pkJ/Wn//lG!%mQ>Ob3U", "!LeSNcjV%qv!apmqePOP:}MBWPCHfdY4IkqO=AW0"); cert.setMeta("version", "1"); StringWriter writer = new StringWriter(); cert.saveSecret(writer); Strin...
public static StatementExecutorResponse execute( final ConfiguredStatement<TerminateQuery> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final TerminateQuery terminateQuery = statement.getStatement...
@Test public void shouldDefaultToDistributorForTerminateCluster() { // Given: final ConfiguredStatement<?> terminatePersistent = engine.configure("TERMINATE CLUSTER;"); final KsqlEngine engine = mock(KsqlEngine.class); // When: final Optional<KsqlEntity> ksqlEntity = CustomExecutors.TERMINATE_QUE...
@Override public SourceReader<Long, NumberSequenceSplit> createReader(SourceReaderContext readerContext) { return new IteratorSourceReader<>(readerContext); }
@Test void testReaderCheckpoints() throws Exception { final long from = 177; final long mid = 333; final long to = 563; final long elementsPerCycle = (to - from) / 3; final TestingReaderOutput<Long> out = new TestingReaderOutput<>(); SourceReader<Long, NumberSequenc...
@Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { this.config = TbNodeUtils.convert(configuration, TbJsonPathNodeConfiguration.class); this.jsonPathValue = config.getJsonPath(); if (!TbJsonPathNodeConfiguration.DEFAULT_JSON_PATH.equals(this...
@Test void givenJsonMsg_whenOnMsg_thenVerifyJavaPrimitiveOutput() throws Exception { config.setJsonPath("$.attributes.length()"); nodeConfiguration = new TbNodeConfiguration(JacksonUtil.valueToTree(config)); node.init(ctx, nodeConfiguration); String data = "{\"attributes\":[{\"attri...
public static TopicPartitionMetadata decode(final String encryptedString) { long timestamp = RecordQueue.UNKNOWN; ProcessorMetadata metadata = new ProcessorMetadata(); if (encryptedString.isEmpty()) { return new TopicPartitionMetadata(timestamp, metadata); } try { ...
@Test public void shouldDecodeEmptyStringVersionTwo() { final TopicPartitionMetadata expected = new TopicPartitionMetadata(RecordQueue.UNKNOWN, new ProcessorMetadata()); final TopicPartitionMetadata topicMeta = TopicPartitionMetadata.decode(""); assertThat(topicMeta, is(expected)); }
@Override public void pushWriteLockedEdge(Inode inode, String childName) { Edge edge = new Edge(inode.getId(), childName); Preconditions.checkState(!endsInInode(), "Cannot push edge write lock to edge %s; lock list %s ends in an inode", edge, this); Preconditions.checkState(endsInWriteLock(), ...
@Test public void pushWriteLockedEdge() { mLockList.lockRootEdge(LockMode.WRITE); assertEquals(LockMode.WRITE, mLockList.getLockMode()); assertTrue(mLockList.getLockedInodes().isEmpty()); mLockList.pushWriteLockedEdge(mRootDir, mDirA.getName()); assertEquals(LockMode.WRITE, mLockList.getLockMode(...
public static String parseToString(Map<String, String> attributes) { if (attributes == null || attributes.size() == 0) { return ""; } List<String> kvs = new ArrayList<>(); for (Map.Entry<String, String> entry : attributes.entrySet()) { String value = entry.getVa...
@Test public void testParseToString() { Assert.assertEquals("", AttributeParser.parseToString(null)); Assert.assertEquals("", AttributeParser.parseToString(newHashMap())); HashMap<String, String> map = new HashMap<>(); int addSize = 10; for (int i = 0; i < addSize; i++) { ...
String getBuildVersion() { return getManifestAttribute("Implementation-Version", "<version_unknown>"); }
@Test public void testRequestedManifestIsLocatedAndLoaded() throws Exception { DiscoveryBuildInfo buildInfo = new DiscoveryBuildInfo(ObjectMapper.class); assertThat(buildInfo.getBuildVersion().contains("version_unknown"), is(false)); }
public static List<CredentialRetriever> getFromCredentialRetrievers( CommonCliOptions commonCliOptions, DefaultCredentialRetrievers defaultCredentialRetrievers) throws FileNotFoundException { // these are all mutually exclusive as enforced by the CLI commonCliOptions .getUsernamePassword() ...
@Test @Parameters(method = "paramsFromNone") public void testGetFromCredentialRetriever_none(String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); Credentials.getFromCredentialRetr...
@Override public void finishSink(String dbName, String tableName, List<TSinkCommitInfo> commitInfos, String branch) { if (commitInfos.isEmpty()) { LOG.warn("No commit info on {}.{} after hive sink", dbName, tableName); return; } HiveTable table = (HiveTable) getTable(...
@Test public void testAppendTable() throws Exception { String stagingDir = "hdfs://127.0.0.1:10000/tmp/starrocks/queryid"; THiveFileInfo fileInfo = new THiveFileInfo(); fileInfo.setFile_name("myfile.parquet"); fileInfo.setPartition_path("hdfs://127.0.0.1:10000/tmp/starrocks/queryid/"...
@Override public ProtocolConfig build() { ProtocolConfig protocolConfig = new ProtocolConfig(); super.build(protocolConfig); protocolConfig.setAccepts(accepts); protocolConfig.setAccesslog(accesslog); protocolConfig.setBuffer(buffer); protocolConfig.setCharset(charse...
@Test void build() { ProtocolBuilder builder = new ProtocolBuilder(); builder.name("name") .host("host") .port(8080) .contextpath("contextpath") .threadpool("mockthreadpool") .corethreads(1) .threads(2) ...
@Override public void write(InputT element, Context context) throws IOException, InterruptedException { while (bufferedRequestEntries.size() >= maxBufferedRequests) { flush(); } addEntryToBuffer(elementConverter.apply(element, context), false); nonBlockingFlush(); }
@Test public void testThatUnwrittenRecordsInBufferArePersistedWhenSnapshotIsTaken() throws IOException, InterruptedException { AsyncSinkWriterImpl sink = new AsyncSinkWriterImplBuilder().context(sinkInitContext).build(); for (int i = 0; i < 23; i++) { sink.wri...
@Override public boolean addTopicConfig(final String topicName, final Map<String, ?> overrides) { final ConfigResource resource = new ConfigResource(ConfigResource.Type.TOPIC, topicName); final Map<String, String> stringConfigs = toStringConfigs(overrides); try { final Map<String, String> existing...
@Test public void shouldSetNonStringTopicConfig() { // Given: givenTopicConfigs( "peter", overriddenConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "12345"), defaultConfigEntry(TopicConfig.COMPRESSION_TYPE_CONFIG, "snappy") ); final Map<String, ?> configOverrides = ImmutableMap.o...
public static Db use() { return use(DSFactory.get()); }
@Test @Disabled public void queryFetchTest() throws SQLException { // https://gitee.com/dromara/hutool/issues/I4JXWN Db.use().query((conn->{ PreparedStatement ps = conn.prepareStatement("select * from table", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ps.setFetchSize(Integer.MIN_VAL...
@Override public void execute(Runnable command) { taskExecutor.execute(new RunnableWrapper<>(command, contextGetter, contextSetter)); }
@Test public void testExecute() { TEST_THREAD_LOCAL.set(TEST); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.initialize(); AtomicReference<Boolean> result = new AtomicReference<>(false); CountDownLatch latch = new CountDownLatch(1); TaskExecutorWrapper<String> taskExecutorWrapper...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final Instant lower = calculateLowerBound(windowSt...
@Test @SuppressWarnings("unchecked") public void shouldReturnValuesForOpenEndBounds_fetchAll() { // Given: final Range<Instant> end = Range.open( NOW, NOW.plusSeconds(10) ); final Range<Instant> startEquiv = Range.open( end.lowerEndpoint().minus(WINDOW_SIZE), end.upperEndpoi...
int parseAndConvert(String[] args) throws Exception { Options opts = createOptions(); int retVal = 0; try { if (args.length == 0) { LOG.info("Missing command line arguments"); printHelp(opts); return 0; } CommandLine cliParser = new GnuParser().parse(opts, args); ...
@Test public void testMissingYarnSiteXmlArgument() throws Exception { setupFSConfigConversionFiles(true); FSConfigToCSConfigArgumentHandler argumentHandler = createArgumentHandler(); String[] args = new String[] {"-o", FSConfigConverterTestCommons.OUTPUT_DIR}; int retVal = argumentH...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { if(0L == status.getLength()) { return new NullInputStream(0L); } final Storage.Objects.Get request = sessi...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final TransferStatus status = new TransferStatus(); final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); new GoogleStorageReadFeature(session).read(...
public byte[] getDir_uuid() { return dir_uuid; }
@Test public void getDir_uuid() { assertNotNull(chmItsfHeader.getDir_uuid()); }
private Schema getSchema() { try { final String schemaString = getProperties().getProperty(SCHEMA); if (schemaString == null) { throw new ParquetEncodingException("Can not store relation in Parquet as the schema is unknown"); } return Utils.getSchemaFromString(schemaString); } ca...
@Test public void testComplexSchema() throws ExecException, Exception { String out = "target/out"; PigServer pigServer = new PigServer(ExecType.LOCAL); Data data = Storage.resetData(pigServer); Collection<Tuple> list = new ArrayList<Tuple>(); for (int i = 0; i < 1000; i++) { list.add(tuple("...