focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Map<String, String> loadProperties(final File propertiesFile) { return loadProperties(ImmutableList.of(propertiesFile)); }
@Test public void shouldLoadPropsFromFile() { // Given: givenPropsFileContains( "# Comment" + System.lineSeparator() + "some.prop=some value" + System.lineSeparator() + "some.other.prop=124" + System.lineSeparator() ); // When: final Map<String, String> result = Pr...
public BlockLease flatten(Block block) { requireNonNull(block, "block is null"); if (block instanceof DictionaryBlock) { return flattenDictionaryBlock((DictionaryBlock) block); } if (block instanceof RunLengthEncodedBlock) { return flattenRunLengthEncodedBlock...
@Test public void testIntArrayIdentityDecode() { Block block = createIntArrayBlock(1, 2, 3, 4); try (BlockLease blockLease = flattener.flatten(block)) { Block flattenedBlock = blockLease.get(); assertSame(flattenedBlock, block); } }
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification( FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters) throws IOException { FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy(); List<HasMetadata> ...
@Test void testDeploymentSpec() throws IOException { kubernetesJobManagerSpecification = KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification( flinkPod, kubernetesJobManagerParameters); final DeploymentSpec resultDeploymentSpec = ...
@Override public String route(final ReadwriteSplittingDataSourceGroupRule rule) { switch (rule.getTransactionalReadQueryStrategy()) { case FIXED: if (!connectionContext.getTransactionContext().getReadWriteSplitReplicaRoute().isPresent()) { connectionContext.ge...
@Test void assertRoute() { ReadwriteSplittingDataSourceGroupRuleConfiguration dataSourceGroupConfig = new ReadwriteSplittingDataSourceGroupRuleConfiguration( "test_config", "write_ds", Arrays.asList("read_ds_0", "read_ds_1"), null); ReadwriteSplittingDataSourceGroupRule rule; ...
@SuppressWarnings("OptionalGetWithoutIsPresent") // Enforced by type @Override public StreamsMaterializedWindowedTable windowed() { if (!windowInfo.isPresent()) { throw new UnsupportedOperationException("Table has non-windowed key"); } final WindowInfo wndInfo = windowInfo.get(); final Window...
@Test public void shouldReturnWindowedForTumbling() { // Given: givenWindowType(Optional.of(WindowType.TUMBLING)); // When: final StreamsMaterializedWindowedTable table = materialization.windowed(); // Then: assertThat(table, is(instanceOf(KsMaterializedWindowTable.class))); }
@Override public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException { throw new UnsupportedOperationException(); }
@Test public void invoke() throws Exception { boolean error = false; try { new ExcludeFilter("*").invoke(null, null); } catch (Exception e) { error = e instanceof UnsupportedOperationException; } Assert.assertTrue(error); }
protected void populateSettings(CliParser cli) throws InvalidSettingException { final File propertiesFile = cli.getFileArgument(CliParser.ARGUMENT.PROP); if (propertiesFile != null) { try { settings.mergeProperties(propertiesFile); } catch (FileNotFoundException e...
@Test public void testPopulatingSuppressionSettingsWithMultipleFiles() throws Exception { // GIVEN CLI properties with the mandatory arguments File prop = new File(this.getClass().getClassLoader().getResource("sample.properties").toURI().getPath()); // AND a single suppression file ...
public void putMulti(MultiItem<T> items) throws Exception { putMulti(items, 0, null); }
@Test public void testPutMulti() throws Exception { final int itemQty = 100; DistributedQueue<TestQueueItem> queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQ...
@Override public Object[] getRowFromCache( RowMetaInterface lookupMeta, Object[] lookupRow ) throws KettleException { if ( stepData.hasDBCondition ) { // actually, there was no sense in executing SELECT from db in this case, // should be reported as improvement return null; } SearchingC...
@Test public void hasDbConditionStopsSearching() throws Exception { stepData.hasDBCondition = true; assertNull( buildCache( "" ).getRowFromCache( keysMeta.clone(), keys[ 0 ] ) ); }
@Override public Result responseMessageForCheckConnectionToRepository(String responseBody) { return jsonResultMessageHandler.toResult(responseBody); }
@Test public void shouldBuildFailureResultFromCheckRepositoryConnectionResponse() throws Exception { String responseBody = "{\"status\":\"failure\",messages=[\"message-one\",\"message-two\"]}"; Result result = messageHandler.responseMessageForCheckConnectionToRepository(responseBody); assert...
@Override public Object adapt(final HttpAction action, final WebContext context) { if (action != null) { var code = action.getCode(); val response = ((JEEContext) context).getNativeResponse(); if (code < 400) { response.setStatus(code); } else...
@Test public void testError500() throws IOException { JEEHttpActionAdapter.INSTANCE.adapt(new StatusAction(500), context); verify(response).sendError(500); }
public void load() { Set<CoreExtension> coreExtensions = serviceLoaderWrapper.load(getClass().getClassLoader()); ensureNoDuplicateName(coreExtensions); coreExtensionRepository.setLoadedCoreExtensions(coreExtensions); if (!coreExtensions.isEmpty()) { LOG.info("Loaded core extensions: {}", coreExte...
@Test public void load_sets_loaded_core_extensions_into_repository() { Set<CoreExtension> coreExtensions = IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newCoreExtension("core_ext_" + i)) .collect(Collectors.toSet()); when(serviceLoaderWrapper.load(any())).thenReturn(coreExtension...
@Override public boolean move(String destination, V member) { return get(moveAsync(destination, member)); }
@Test public void testMove() throws Exception { RSet<Integer> set = redisson.getSet("set"); RSet<Integer> otherSet = redisson.getSet("otherSet"); set.add(1); set.add(2); assertThat(set.move("otherSet", 1)).isTrue(); assertThat(set.size()).isEqualTo(1); asse...
public static String stripSchemeAndOptions(Endpoint endpoint) { int start = endpoint.getEndpointUri().indexOf(':'); start++; // Remove any leading '/' while (endpoint.getEndpointUri().charAt(start) == '/') { start++; } int end = endpoint.getEndpointUri().index...
@Test public void testStripSchemeNoOptionsWithSlashes() { Endpoint endpoint = Mockito.mock(Endpoint.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("direct://hello"); assertEquals("hello", AbstractSpanDecorator.stripSchemeAndOptions(endpoint)); }
@Override public Local create(final Path file) { return this.create(String.format("%s-%s", new AlphanumericRandomStringService().random(), file.getName())); }
@Test public void testCreateFile() { final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator); final String s = System.getProperty("file.separator"); assertEquals(String.format("%s%su%s1742810335-f", temp, s, s), new FlatTemporaryFileSer...
@VisibleForTesting ImmutableList<AggregationKeyResult> extractValues(PivotResult pivotResult) throws EventProcessorException { final ImmutableList.Builder<AggregationKeyResult> results = ImmutableList.builder(); // Example PivotResult structures. The row value "key" is composed of: "metric/<functio...
@Test public void testExtractValuesWithNullValues() throws Exception { final long WINDOW_LENGTH = 30000; final AbsoluteRange timerange = AbsoluteRange.create(DateTime.now(DateTimeZone.UTC).minusSeconds(3600), DateTime.now(DateTimeZone.UTC)); final SeriesSpec seriesCount = Count.builder().id(...
protected ChannelPoolHandler handler() { return handler; }
@Test public void testHandler() { final ChannelPoolHandler handler = new CountingChannelPoolHandler(); final SimpleChannelPool pool = new SimpleChannelPool(new Bootstrap(), handler); try { assertSame(handler, pool.handler()); } finally { pool.close(); ...
@Override public HttpResponse get() throws InterruptedException, ExecutionException { try { final Object result = process(0, null); if (result instanceof Throwable) { throw new ExecutionException((Throwable) result); } return (HttpResponse) res...
@Test(expected = TimeoutException.class) public void errGetTimeoutEx() throws ExecutionException, InterruptedException, TimeoutException { get(new TimeoutException(), true); }
public static String getInterfaceName(Invoker invoker) { return getInterfaceName(invoker, false); }
@Test public void testGetInterfaceNameWithPrefix() throws NoSuchMethodException { URL url = URL.valueOf("dubbo://127.0.0.1:2181") .addParameter(CommonConstants.VERSION_KEY, "1.0.0") .addParameter(CommonConstants.GROUP_KEY, "grp1") .addParameter(CommonConstants...
@Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return lessIsBetter ? criterionValue1.isLessThan(criterionValue2) : criterionValue1.isGreaterThan(criterionValue2); }
@Test public void betterThanWithLessIsBetter() { AnalysisCriterion criterion = getCriterion(new ProfitLossCriterion()); assertFalse(criterion.betterThan(numOf(5000), numOf(4500))); assertTrue(criterion.betterThan(numOf(4500), numOf(5000))); }
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testCurrentLocationHourlyQuery() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setMode(WeatherMode.XML); weatherConfiguration.setPeriod("3"); weatherConfiguration.setLanguage(WeatherLanguage.nl); ...
static int tableSizeFor(int cap) { int n = ALL_BIT_IS_ONE >>> Integer.numberOfLeadingZeros(cap - 1); return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
@Test public void testTableSizeFor() { int maxCap = 1 << 30; for (int i = 0; i <= maxCap; i++) { int tabSize1 = tabSizeFor_JDK8(i); int tabSize2 = TaskTimeRecordPlugin.tableSizeFor(i); Assert.assertTrue(tabSize1 == tabSize2); } }
@Override public int run(String[] args) throws Exception { YarnConfiguration yarnConf = getConf() == null ? new YarnConfiguration() : new YarnConfiguration( getConf()); boolean isHAEnabled = yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED, YarnConfiguration.DEFAULT_...
@Test public void testCheckHealth() throws Exception { String[] args = {"-checkHealth", "rm1"}; // RM HA is disabled. // getServiceState should not be executed assertEquals(-1, rmAdminCLI.run(args)); verify(haadmin, never()).monitorHealth(); // Now RM HA is enabled. // getServiceState sh...
public Optional<Boolean> getBasicConstraints() { return getExtensions() .map(BasicConstraints::fromExtensions) .map(BasicConstraints::isCA); }
@Test void can_read_basic_constraints() { X500Principal subject = new X500Principal("CN=subject"); KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256); Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA) .setBasicC...
@NonNull public static GestureTypingPathDraw create( @NonNull OnInvalidateCallback callback, @NonNull GestureTrailTheme theme) { if (theme.maxTrailLength <= 0) return NO_OP; return new GestureTypingPathDrawHelper(callback, theme); }
@Test public void testCreatesNoOp() { final AtomicInteger invalidates = new AtomicInteger(); Assert.assertSame( GestureTypingPathDrawHelper.NO_OP, GestureTypingPathDrawHelper.create( invalidates::incrementAndGet, new GestureTrailTheme( Color.argb(200, 60...
@Override public URL getResource(String name) { ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resource '{}'", name); for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) { URL url = null; ...
@Test void parentLastGetResourceExistsInParent() throws IOException, URISyntaxException { URL resource = parentLastPluginClassLoader.getResource("META-INF/file-only-in-parent"); assertFirstLine("parent", resource); }
static boolean needWrap(MethodDescriptor methodDescriptor, Class<?>[] parameterClasses, Class<?> returnClass) { String methodName = methodDescriptor.getMethodName(); // generic call must be wrapped if (CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName)...
@Test void testBiStream() throws Exception { Method method = DescriptorService.class.getMethod("bidirectionalStream", StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(1, descriptor.getParameterClasses().length); ...
public static JSON parse(Object obj) { return parse(obj, null); }
@Test public void parseTest() { assertThrows(JSONException.class, () -> { final JSONArray jsonArray = JSONUtil.parseArray("[{\"a\":\"a\\x]"); Console.log(jsonArray); }); }
public static void executeWithRetries( final Function function, final RetryBehaviour retryBehaviour ) throws Exception { executeWithRetries(() -> { function.call(); return null; }, retryBehaviour); }
@Test public void shouldRetryAndEventuallyThrowIfNeverSucceeds() throws Exception { // Given: final Callable<Object> neverSucceeds = () -> { throw new ExecutionException(new TestRetriableException("I will never succeed")); }; // When: final ExecutionException e = assertThrows( Execu...
@Override public Map<String, NoteInfo> list(AuthenticationInfo subject) throws IOException { // Must to create rootNotebookFileObject each time when call method list, otherwise we can not // get the updated data under this folder. this.rootNotebookFileObject = fsManager.resolveFile(this.rootNotebookFolder...
@Test void testSkipInvalidFileName() throws IOException { assertEquals(0, notebookRepo.list(AuthenticationInfo.ANONYMOUS).size()); createNewNote("{}", "hidden_note", "my_project/.hidden_note"); Map<String, NoteInfo> noteInfos = notebookRepo.list(AuthenticationInfo.ANONYMOUS); assertEquals(0, noteInf...
@Override public List<SnowflakeIdentifier> listDatabases() { List<SnowflakeIdentifier> databases; try { databases = connectionPool.run( conn -> queryHarness.query( conn, "SHOW DATABASES IN ACCOUNT", DATABASE_RESULT_SET_HANDLER)); } catc...
@SuppressWarnings("unchecked") @Test public void testListDatabasesSQLExceptionAtRootLevel() throws SQLException, InterruptedException { Exception injectedException = new SQLException(String.format("SQL exception with Error Code %d", 0), "2000", 0, null); when(mockClientPool.run(any(ClientPool.Action...
@Override public Base64BinaryChunk parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException { String streamId = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_STREAM_ID); String nrString = parser.getAttributeValue("", Base64Bin...
@Test public void isLatsChunkParsedCorrectly() throws Exception { String base64Text = "2uPzi9u+tVWJd+e+y1AAAAABJRU5ErkJggg=="; String string = "<chunk xmlns='urn:xmpp:http' streamId='Stream0001' nr='1' last='true'>" + base64Text + "</chunk>"; Base64BinaryChunkProvider provider = new Base64B...
protected static List<String> getParameters(String path) { List<String> parameters = null; int startIndex = path.indexOf('{'); while (startIndex != -1) { int endIndex = path.indexOf('}', startIndex); if (endIndex != -1) { if (parameters == null) { ...
@Test public void testGetParameters() { assertEquals(Arrays.asList("id1", "id2"), RestSpanDecorator.getParameters("/context/{id1}/{id2}")); }
public static boolean isRumResource(String resourceName) { return BOOMERANG_FILENAME.equals(resourceName); }
@Test public void testIsRumResource() { assertTrue("isRumResource", RumInjector.isRumResource("boomerang.min.js")); assertFalse("isRumResource", RumInjector.isRumResource("notboomerang")); }
public boolean hasProjectSubscribersForTypes(String projectUuid, Set<Class<? extends Notification>> notificationTypes) { Set<String> dispatcherKeys = handlers.stream() .filter(handler -> notificationTypes.stream().anyMatch(notificationType -> handler.getNotificationClass() == notificationType)) .map(Not...
@Test public void hasProjectSubscribersForType_returns_false_if_set_is_empty() { String dispatcherKey1A = randomAlphabetic(5); String dispatcherKey1B = randomAlphabetic(6); String projectUuid = randomAlphabetic(7); NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Not...
public double getRelevance() { return relevance; }
@Test void testRelevanceIsKeptEvenWithBySortData() { assertEquals(1.3, new LeanHit(gidA, 0, 0, 1.3, gidA).getRelevance(), 0.0); }
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); DoubleColumnStatsDataInspector aggregateData = doubleInspectorFromStats(aggregateColStats); Doubl...
@Test public void testMergeNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(double.class) .low(null) .high(null) .numNulls(1) .numDVs(0) .build()); merger.merge(aggrObj, aggrObj); ColumnStatisticsData expectedColumnStatis...
@Override @TpsControl(pointName = "ConfigQuery") @Secured(action = ActionTypes.READ, signType = SignType.CONFIG) @ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class) public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException { ...
@Test void testGetTagNotFound() throws Exception { final String groupKey = GroupKey2.getKey(dataId, group, ""); String content = "content_from_tag_withtagÄãºÃ" + System.currentTimeMillis(); ConfigRocksDbDiskService configRocksDbDiskService = Mockito.mock(ConfigRocksDbDiskService.cla...
@Override public BaseCombineOperator run() { try (InvocationScope ignored = Tracing.getTracer().createScope(CombinePlanNode.class)) { return getCombineOperator(); } }
@Test public void testSlowPlanNode() { AtomicBoolean notInterrupted = new AtomicBoolean(); List<PlanNode> planNodes = new ArrayList<>(); for (int i = 0; i < 20; i++) { planNodes.add(() -> { try { Thread.sleep(10000); } catch (InterruptedException e) { // Thread s...
private boolean isContainsEnhancedTable(final ShardingSphereMetaData metaData, final Collection<String> databaseNames, final String currentDatabaseName) { for (String each : databaseNames) { if (isContainsEnhancedTable(metaData, each, getTablesContext().getTableNames())) { return tru...
@Test void assertIsContainsEnhancedTable() { ProjectionsSegment projectionsSegment = new ProjectionsSegment(0, 0); projectionsSegment.getProjections().add(new ColumnProjectionSegment(new ColumnSegment(0, 0, new IdentifierValue("order_id")))); SelectStatement selectStatement = new MySQLSelect...
public DropSourceCommand create(final DropStream statement) { return create( statement.getName(), statement.getIfExists(), statement.isDeleteTopic(), DataSourceType.KSTREAM ); }
@Test public void shouldFailDropSourceOnMissingSourceWithNoIfExistsForTable() { // Given: final DropTable dropTable = new DropTable(SOME_NAME, false, true); when(metaStore.getSource(SOME_NAME)).thenReturn(null); // When: final Exception e = assertThrows( KsqlException.class, () ->...
@SuppressWarnings("ConstantConditions") public boolean removeActions(@NonNull Class<? extends Action> clazz) { if (clazz == null) { throw new IllegalArgumentException("Action type must be non-null"); } // CopyOnWriteArrayList does not support Iterator.remove, so need to do it thi...
@Test public void removeActions_null() { assertThrows(IllegalArgumentException.class, () -> thing.removeActions(null)); }
static void validateFileExtension(Path jarPath) { String fileName = jarPath.getFileName().toString(); if (!fileName.endsWith(".jar")) { throw new JetException("File name extension should be .jar"); } }
@Test public void invalidFileExtension() { Path jarPath1 = Paths.get("/mnt/foo"); assertThatThrownBy(() -> SubmitJobParametersValidator.validateFileExtension(jarPath1)) .isInstanceOf(JetException.class) .hasMessageContaining("File name extension should be .jar"); ...
public void validateDocumentGraph(List<SDDocumentType> documents) { for (SDDocumentType document : documents) { validateRoot(document); } }
@Test void self_reference_is_forbidden() { Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> { Schema adSchema = createSearchWithName("ad"); createDocumentReference(adSchema, adSchema, "ad_ref"); DocumentGraphValidator validato...
public static String prepareUrl(@NonNull String url) { url = url.trim(); String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive if (lowerCaseUrl.startsWith("feed://")) { Log.d(TAG, "Replacing feed:// with http://"); return prepareUrl(ur...
@Test public void testAntennaPodSubscribeProtocolWithScheme() { final String in = "antennapod-subscribe://https://example.com"; final String out = UrlChecker.prepareUrl(in); assertEquals("https://example.com", out); }
@Override public AuthorizationPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { Capabilities capabilities = capabilities(descriptor.id()); PluggableInstanceSettings authConfigSettings = authConfigSettings(descriptor.id()); PluggableInstanceSettings roleSettings = roleSettings(descri...
@Test public void shouldBuildPluginInfoWithCapablities() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); Capabilities capabilities = new Capabilities(SupportedAuthType.Password, true, true, false); when(extension.getCapabilities(descriptor.id())).thenRe...
static QueryId buildId( final Statement statement, final EngineContext engineContext, final QueryIdGenerator idGenerator, final OutputNode outputNode, final boolean createOrReplaceEnabled, final Optional<String> withQueryId) { if (withQueryId.isPresent()) { final String que...
@Test public void shouldGenerateUniqueRandomIdsForTransientQueries() { // Given: when(transientPlan.getSinkName()).thenReturn(Optional.empty()); when(transientPlan.getSource()).thenReturn(planNode); when(planNode.getLeftmostSourceNode()).thenReturn(dataSourceNode); when(dataSourceNode.getAlias())....
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials) { final String[] parts = requireNonNull(credentials).password().split(DELIMITER); final String timestampSeconds; final String actualSignature; // making sure password format matches our expectations based on the...
@Test public void testValidateInvalid() throws Exception { final ExternalServiceCredentials corruptedStandardUsername = new ExternalServiceCredentials( standardCredentials.username(), standardCredentials.password().replace(E164, E164 + "0")); final ExternalServiceCredentials corruptedStandardTimestamp...
@Override public URL getLocalArtifactUrl(DependencyJar dependency) { return delegate.getLocalArtifactUrl(dependency); }
@Test public void whenRobolectricDepsPropertiesResource() throws Exception { Path depsPath = tempDirectory.createFile( "deps.properties", "org.robolectric\\:android-all\\:" + VERSION + ": file-123.jar"); when(mockClassLoader.getResource("robolectric-deps.properties")).thenReturn(meh(depsP...
public static UserGroupInformation getUGI(HttpServletRequest request, Configuration conf) throws IOException { return getUGI(null, request, conf); }
@Test public void testGetUgiFromToken() throws IOException { conf.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://localhost:4321/"); ServletContext context = mock(ServletContext.class); String realUser = "TheDoctor"; String user = "TheNurse"; conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "...
public void setSendFullErrorException(boolean sendFullErrorException) { this.sendFullErrorException = sendFullErrorException; }
@Test void handleFlowableIllegalArgumentExceptionWithoutSendFullErrorException() throws Exception { testController.exceptionSupplier = () -> new FlowableIllegalArgumentException("task name is mandatory"); handlerAdvice.setSendFullErrorException(false); String body = mockMvc.perform(get("/")...
@Override public TypeInformation<T> getProducedType() { return type; }
@Test void testTypeExtractionGeneric() { TypeInformation<JSONPObject> type = new JsonSchema().getProducedType(); TypeInformation<JSONPObject> expected = TypeInformation.of(new TypeHint<JSONPObject>() {}); assertThat(type).isEqualTo(expected); }
public static short translateBucketAcl(GSAccessControlList acl, String userId) { short mode = (short) 0; for (GrantAndPermission gp : acl.getGrantAndPermissions()) { Permission perm = gp.getPermission(); GranteeInterface grantee = gp.getGrantee(); if (perm.equals(Permission.PERMISSION_READ)) {...
@Test public void translateUserWritePermission() { mAcl.grantPermission(mUserGrantee, Permission.PERMISSION_WRITE); assertEquals((short) 0200, GCSUtils.translateBucketAcl(mAcl, ID)); mAcl.grantPermission(mUserGrantee, Permission.PERMISSION_READ); assertEquals((short) 0700, GCSUtils.translateBucketAcl(...
public static void main(String[] args) { String relDir = args.length == 1 ? args[0] : ""; graphhopperLocationIndex(relDir); lowLevelLocationIndex(); }
@Test public void main() { LocationIndexExample.main(new String[]{"../"}); }
@Override public void collect(long elapsedTime, StatementContext ctx) { final Timer timer = getTimer(ctx); timer.update(elapsedTime, TimeUnit.NANOSECONDS); }
@Test public void updatesTimerForContextGroupAndName() throws Exception { final StatementNameStrategy strategy = new SmartNameStrategy(); final InstrumentedTimingCollector collector = new InstrumentedTimingCollector(registry, ...
public static FusedPipeline fuse(Pipeline p) { return new GreedyPipelineFuser(p).fusedPipeline; }
@Test public void parDoWithStateAndTimerRootsStage() { PTransform timerTransform = PTransform.newBuilder() .setUniqueName("TimerParDo") .putInputs("input", "impulse.out") .putInputs("timer", "timer.out") .putOutputs("timer", "timer.out") .putOutp...
public List<String> toCollection() { return new ArrayList<>(matchers); }
@Test void shouldReturnMatchersAsArray() { assertThat(new Matcher("JH,Pavan").toCollection()).isEqualTo(Arrays.asList("JH", "Pavan")); }
@Override protected String ruleHandler() { return ""; }
@Test public void testRuleHandler() { assertEquals(StringUtils.EMPTY, shenyuClientRegisterMotanService.ruleHandler()); }
public String getUser() { return user; }
@Test public void getUser() { assertEquals(USER, context.getUser()); }
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_screenLayoutLong_notlong() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("notlong", config); assertThat(config.screenLayout).isEqualTo(SCREENLONG_NO); }
@Override public int hashCode() { return Objects.hash(uuid); }
@Test void hashCode_whenEmptyObjects_shouldBeTheSame() { PortfolioDto p1 = new PortfolioDto(); PortfolioDto p2 = new PortfolioDto(); int hash1 = p1.hashCode(); int hash2 = p2.hashCode(); assertThat(hash1).isEqualTo(hash2); }
public static int timeToSecond(String timeStr) { if (StrUtil.isEmpty(timeStr)) { return 0; } final List<String> hms = StrUtil.splitTrim(timeStr, StrUtil.C_COLON, 3); int lastIndex = hms.size() - 1; int result = 0; for (int i = lastIndex; i >= 0; i--) { result += Integer.parseInt(hms.get(i)) * Math.p...
@Test public void timeToSecondTest() { int second = DateUtil.timeToSecond("00:01:40"); assertEquals(100, second); second = DateUtil.timeToSecond("00:00:40"); assertEquals(40, second); second = DateUtil.timeToSecond("01:00:00"); assertEquals(3600, second); second = DateUtil.timeToSecond("00:00:00"); ass...
public Integer doCall() throws Exception { // Operator id must be set if (ObjectHelper.isEmpty(operatorId)) { printer().println("Operator id must be set"); return -1; } List<String> integrationSources = Stream.concat(Arrays.stream(Optional.ofNulla...
@Test public void shouldAddTraits() throws Exception { IntegrationRun command = createCommand(); command.filePaths = new String[] { "classpath:route.yaml" }; command.traits = new String[] { "logging.level=DEBUG", "container.image-pull-policy=Always" }; command.output = "yaml"; ...
@Deprecated public static FileInputList createFolderList( VariableSpace space, String[] folderName, String[] folderRequired ) { return createFolderList( DefaultBowl.getInstance(), space, folderName, folderRequired ); }
@Test public void testCreateFolderList() throws Exception { buildTestFolderTree(); String[] folderNameList = { tempFolder.getRoot().getPath() }; String[] folderRequiredList = { "N" }; VariableSpace spaceMock = mock( VariableSpace.class ); when( spaceMock.environmentSubstitute( any( String[].class ...
public static String getLogicIndexName(final String actualIndexName, final String actualTableName) { String indexNameSuffix = UNDERLINE + actualTableName; return actualIndexName.endsWith(indexNameSuffix) ? actualIndexName.substring(0, actualIndexName.lastIndexOf(indexNameSuffix)) : actualIndexName; ...
@Test void assertGetLogicIndexNameWithIndexNameSuffix() { assertThat(IndexMetaDataUtils.getLogicIndexName("order_index_t_order", "t_order"), is("order_index")); }
@Override public Object getNativeDataType( Object object ) throws KettleValueException { return getInternetAddress( object ); }
@Test public void testGetNativeDataType() throws UnknownHostException, KettleValueException { ValueMetaInterface vmi = new ValueMetaInternetAddress( "Test" ); InetAddress expected = InetAddress.getByAddress( new byte[] { (byte) 192, (byte) 168, 1, 1 } ); assertEquals( ValueMetaInterface.TYPE_INET, vmi.ge...
@Deprecated @Restricted(DoNotUse.class) public static String resolve(ConfigurationContext context, String toInterpolate) { return context.getSecretSourceResolver().resolve(toInterpolate); }
@Test public void resolve_Json() { String input = "{ \"a\": 1, \"b\": 2 }"; environment.set("FOO", input); String output = resolve("${json:a:${FOO}}"); assertThat(output, equalTo("1")); }
public List<String> splitSql(String text) { List<String> queries = new ArrayList<>(); StringBuilder query = new StringBuilder(); char character; boolean multiLineComment = false; boolean singleLineComment = false; boolean singleQuoteString = false; boolean doubleQuoteString = false; fo...
@Test void testCommentAtEnd() { String sql = "\n" + "select\n" + " 'one'\n" + " , 'two' -- comment\n"; SqlSplitter sqlSplitter = new SqlSplitter(); List<String> sqls = sqlSplitter.splitSql(sql); assertEquals(1, sqls.size()); assertEquals("\n" + "se...
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not f...
@Test public void testStaticMemberRejoinAsFollowerWithKnownMemberIdAndNoProtocolChange() throws Exception { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticM...
public int filterEntriesForConsumer(List<? extends Entry> entries, EntryBatchSizes batchSizes, SendMessageInfo sendMessageInfo, EntryBatchIndexesAcks indexesAcks, ManagedCursor cursor, boolean isReplayRead, Consumer consumer) { return filterEntriesForConsumer(null, 0, entries, batchSizes...
@Test public void testFilterEntriesForConsumerOfTxnBufferAbort() { PersistentTopic mockTopic = mock(PersistentTopic.class); when(this.subscriptionMock.getTopic()).thenReturn(mockTopic); when(mockTopic.isTxnAborted(any(TxnID.class), any())).thenReturn(true); List<Entry> entries = ne...
@Override public void createService(Service service, AbstractSelector selector) throws NacosException { }
@Test void testCreateService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); Service service = new Service(); AbstractSelector selector = new NoneSelector(); client.createService(service, selector); }
public String sendPostData(URLConnection connection, HTTPSamplerBase sampler) throws IOException { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); HTTPFileArg[] files = sampler.getHTTPFiles(); String contentEncoding = sampler.get...
@Test public void testSendPostData() throws IOException { sampler.setMethod(HTTPConstants.POST); setupFilepart(sampler); String titleValue = "mytitle"; String descriptionValue = "mydescription"; setupFormData(sampler, titleValue, descriptionValue); // Test sending da...
List<StatisticsEntry> takeStatistics() { if (reporterEnabled) throw new IllegalStateException("Cannot take consistent snapshot while reporter is enabled"); var ret = new ArrayList<StatisticsEntry>(); consume((metric, value) -> ret.add(new StatisticsEntry(metric, value))); ret...
@Test void statistics_include_grouped_and_single_statuscodes() { testRequest("http", 401, "GET"); testRequest("http", 404, "GET"); testRequest("http", 403, "GET"); var stats = collector.takeStatistics(); assertStatisticsEntry(stats, "http", "GET", MetricDefinitions.RESPONSES...
public static InboundEdgeStream create( @Nonnull ConcurrentConveyor<Object> conveyor, int ordinal, int priority, boolean waitForAllBarriers, @Nonnull String debugName, @Nullable ComparatorEx<?> comparator ) { if (comparator == null) { ...
@Test public void when_receivingBarriersWhileDone_then_coalesce() { stream = ConcurrentInboundEdgeStream.create(conveyor, 0, 0, true, "cies", null); add(q1, 1, barrier(0)); add(q2, DONE_ITEM); drainAndAssert(MADE_PROGRESS, 1); drainAndAssert(MADE_PROGRESS, barrier(0)); ...
@Override public KsMaterializedQueryResult<Row> get( final GenericKey key, final int partition, final Optional<Position> position ) { try { final ReadOnlyKeyValueStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore .store(QueryableStoreTypes.timestampedKeyValueSt...
@Test public void shouldGetWithCorrectParams() { // When: table.get(A_KEY, PARTITION); // Then: verify(tableStore).get(A_KEY); }
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testPkcs1Des3EncryptedRsaNoPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypt...
@Override public void deleteTenantPackage(Long id) { // 校验存在 validateTenantPackageExists(id); // 校验正在使用 validateTenantUsed(id); // 删除 tenantPackageMapper.deleteById(id); }
@Test public void testDeleteTenantPackage_success() { // mock 数据 TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class); tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbTenantPackage.getId(); // mock 租户未使用该套餐 w...
@Override public String getWelcomeMessage(final User user) { if (isEnhanced()) { return "Welcome " + user + ". You're using the enhanced welcome message."; } return "Welcome to the application."; }
@Test void testFeatureTurnedOn() { final var properties = new Properties(); properties.put("enhancedWelcome", true); var service = new PropertiesFeatureToggleVersion(properties); assertTrue(service.isEnhanced()); final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); ...
public Arguments parse(String[] args) { JCommander jCommander = new JCommander(this); jCommander.setProgramName("jsonschema2pojo"); try { jCommander.parse(args); if (this.showHelp) { jCommander.usage(); exit(EXIT_OKAY); } els...
@Test public void requestingHelpCausesHelp() { ArgsForTest args = (ArgsForTest) new ArgsForTest().parse(new String[] { "--help" }); assertThat(args.status, is(notNullValue())); assertThat(new String(systemOutCapture.toByteArray(), StandardCharsets.UTF_8), is(containsString("Usage: jsonschem...
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback); return bean; }
@Test void beansWithMethodsUsingJobContextAnnotatedWithRecurringCronAnnotationWillAutomaticallyBeRegistered() { // GIVEN final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor(); // WHEN recurringJobPostProcessor.postProcessAfterInitialization(new M...
public static <N> void merge(MutableGraph<N> graph1, Graph<N> graph2) { for (N node : graph2.nodes()) { graph1.addNode(node); } for (EndpointPair<N> edge : graph2.edges()) { graph1.putEdge(edge.nodeU(), edge.nodeV()); } }
@Test public void mergeDistinctGraphs() { final MutableGraph<String> graph1 = GraphBuilder.directed().build(); graph1.addNode("Test1"); graph1.addNode("Test2"); graph1.putEdge("Test1", "Test2"); final MutableGraph<String> graph2 = GraphBuilder.directed().build(); gra...
public static List<FieldInfo> buildSourceSchemaEntity(final LogicalSchema schema) { final List<FieldInfo> allFields = schema.columns().stream() .map(EntityUtil::toFieldInfo) .collect(Collectors.toList()); if (allFields.isEmpty()) { throw new IllegalArgumentException("Root schema should co...
@Test public void shouldSupportSchemasWithKeyColumns() { // Given: final LogicalSchema schema = LogicalSchema.builder() .keyColumn(ColumnName.of("field1"), SqlTypes.INTEGER) .build(); // When: final List<FieldInfo> fields = EntityUtil.buildSourceSchemaEntity(schema); // Then: ...
@Override protected String getInstanceClassName() { return ""; }
@Test public void getInstanceClassName() { }
@Override public Credentials configure(final Host host) { if(StringUtils.isNotBlank(host.getHostname())) { final Credentials credentials = new Credentials(host.getCredentials()); configuration.refresh(); // Update this host credentials from the OpenSSH configuration file ...
@Test public void testNoConfigure() { OpenSSHCredentialsConfigurator c = new OpenSSHCredentialsConfigurator( new OpenSshConfig( new Local("src/main/test/resources", "openssh/config"))); Credentials credentials = new Credentials("user", " "); credentials.setIdentit...
static Object actualCoerceParameter(Type requiredType, Object valueToCoerce) { Object toReturn = valueToCoerce; if (valueToCoerce instanceof LocalDate localDate && requiredType == BuiltInType.DATE_TIME) { return DateTimeEvalHelper.coerceDateTime(localDate); } ...
@Test void actualCoerceParameterToDateTimeConverted() { Object value = LocalDate.now(); Object retrieved = CoerceUtil.actualCoerceParameter(BuiltInType.DATE_TIME, value); assertNotNull(retrieved); assertTrue(retrieved instanceof ZonedDateTime); ZonedDateTime zdtRetrieved = (Z...
public static DataSource createDataSource(final ModeConfiguration modeConfig) throws SQLException { return createDataSource(DefaultDatabase.LOGIC_NAME, modeConfig); }
@Test void assertCreateDataSourceWithAllParametersForSingleDataSource() throws SQLException { assertDataSource(ShardingSphereDataSourceFactory.createDataSource("test_db", new ModeConfiguration("Standalone", null), new MockedDataSource(), new LinkedList<>(), new Properties()), "test_db"); ...
@Override public Set<EntityExcerpt> listEntityExcerpts() { return inputService.all().stream() .map(InputWithExtractors::create) .map(this::createExcerpt) .collect(Collectors.toSet()); }
@Test @MongoDBFixtures("InputFacadeTest.json") public void listEntityExcerpts() { final EntityExcerpt expectedEntityExcerpt1 = EntityExcerpt.builder() .id(ModelId.of("5adf25294b900a0fdb4e5365")) .type(ModelTypes.INPUT_V1) .title("Global Random HTTP") ...
@Override public void renameTable(TableIdentifier from, TableIdentifier to) { if (!namespaceExists(to.namespace())) { throw new NoSuchNamespaceException( "Cannot rename %s to %s because namespace %s does not exist", from, to, to.namespace()); } if (tableExists(to)) { throw new Alrea...
@Test public void testRenameTable() { ecsCatalog.createNamespace(Namespace.of("a")); ecsCatalog.createTable(TableIdentifier.of("a", "t1"), SCHEMA); ecsCatalog.createNamespace(Namespace.of("b")); assertThatThrownBy( () -> ecsCatalog.renameTable( TableIde...
public void logAndProcessFailure( String computationId, ExecutableWork executableWork, Throwable t, Consumer<Work> onInvalidWork) { if (shouldRetryLocally(computationId, executableWork.work(), t)) { // Try again after some delay and at the end of the queue to avoid a tight loop. ...
@Test public void logAndProcessFailure_doesNotRetryKeyTokenInvalidException() { Set<Work> executedWork = new HashSet<>(); ExecutableWork work = createWork(executedWork::add); WorkFailureProcessor workFailureProcessor = createWorkFailureProcessor(streamingEngineFailureReporter()); Set<Work> inv...
public Iterator<ReadRowsResponse> readRows() { List<ReadRowsResponse> readRowResponses = new ArrayList<>(); long readRowsCount = 0; int retries = 0; Iterator<ReadRowsResponse> serverResponses = fetchResponses(request); while (serverResponses.hasNext()) { try { ...
@Test void testRetryOfSingleFailure() { MockResponsesBatch batch1 = new MockResponsesBatch(); batch1.addResponse(Storage.ReadRowsResponse.newBuilder().setRowCount(10).build()); batch1.addException(new StatusRuntimeException(Status.INTERNAL.withDescription( "Received unexp...
ControllerResult<Map<ConfigResource, ApiError>> incrementalAlterConfigs( Map<ConfigResource, Map<String, Entry<OpType, String>>> configChanges, boolean newlyCreatedResource ) { List<ApiMessageAndVersion> outputRecords = BoundedList.newArrayBacked(MAX_RECORDS_PER_USER_OP); ...
@Test public void testIncrementalAlterConfigs() { ConfigurationControlManager manager = new ConfigurationControlManager.Builder(). setKafkaConfigSchema(SCHEMA). build(); ControllerResult<Map<ConfigResource, ApiError>> result = manager. incrementalAlterConfigs(toM...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldDeserializedJsonNumberAsBigDecimal() { // Given: final KsqlJsonDeserializer<BigDecimal> deserializer = givenDeserializerForSchema(DecimalUtil.builder(20, 19).build(), BigDecimal.class); final List<String> validCoercions = ImmutableList.of( "1.1234512345123451234",...
@Override public void execute(ComputationStep.Context context) { // no notification on pull requests as there is no real Quality Gate on those if (analysisMetadataHolder.isPullRequest()) { return; } executeForProject(treeRootHolder.getRoot()); }
@Test public void no_event_created_if_raw_ALERT_STATUS_measure_is_unsupported_value() { when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().create(INVALID_ALERT_STATUS))); underTest.execute(new TestComputationStepContext()); verify(measur...
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName); if (keyProperties == null) { keyProperties = new LinkedHashMap<>(); String properties = mbeanName.getKeyPropertyListS...
@Test public void testQuotedObjectName() throws Throwable { JmxMBeanPropertyCache testCache = new JmxMBeanPropertyCache(); LinkedHashMap<String, String> parameterList = testCache.getKeyPropertyList( new ObjectName("com.organisation:name=value,name2=\"value2\""...
@Override public void alert(Anomaly anomaly, boolean autoFixTriggered, long selfHealingStartTime, AnomalyType anomalyType) { super.alert(anomaly, autoFixTriggered, selfHealingStartTime, anomalyType); if (_alertaApiUrl == null) { LOG.warn("Alerta API URL is null, can't send Alerta.io self healing notifi...
@Test public void testAlertaAlertWithNoWebhook() { _notifier = new MockAlertaSelfHealingNotifier(mockTime); _notifier.alert(failures, false, 1L, KafkaAnomalyType.BROKER_FAILURE); assertEquals(0, _notifier.getAlertaMessageList().size()); }
public static List<Metadata> fromJson(Reader reader) throws IOException { List<Metadata> ms = null; if (reader == null) { return ms; } ms = new ArrayList<>(); try (JsonParser jParser = new JsonFactory() .setStreamReadConstraints(StreamReadConstraints ...
@Test public void testSwitchingOrderOfMainDoc() throws Exception { Metadata m1 = new Metadata(); m1.add("k1", "v1"); m1.add("k1", "v2"); m1.add("k1", "v3"); m1.add("k1", "v4"); m1.add("k1", "v4"); m1.add("k2", "v1"); m1.add(TikaCoreProperties.EMBEDDED_...
public FileSystem get(Key key) { synchronized (mLock) { Value value = mCacheMap.get(key); FileSystem fs; if (value == null) { // On cache miss, create and insert a new FileSystem instance, fs = FileSystem.Factory.create(FileSystemContext.create(key.mSubject, key.mConf)); mC...
@Test public void getTwiceThenClose() throws IOException { Key key1 = createTestFSKey("user1"); FileSystem fs1 = mFileSystemCache.get(key1); FileSystem fs2 = mFileSystemCache.get(key1); fs1.close(); FileSystem fs3 = mFileSystemCache.get(key1); assertSame(getDelegatedFileSystem(fs2), getDelegat...
boolean isEnabled() { return enabled; }
@Test public void testBackPressureDisabledByDefault() { Config config = new Config(); HazelcastProperties hazelcastProperties = new HazelcastProperties(config); BackpressureRegulator regulator = new BackpressureRegulator(hazelcastProperties, logger); assertFalse(regulator.isEnabled()...
public boolean isInvalid() { return getPathComponents().length <= 1 && !isRoot(); }
@Test public void testInvalidPath() { Assert.assertFalse(TEST_QUEUE_PATH.isInvalid()); Assert.assertFalse(ROOT_PATH.isInvalid()); Assert.assertTrue(EMPTY_PATH.isInvalid()); Assert.assertTrue(new QueuePath("invalidPath").isInvalid()); }
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenShortWithSurroundingSpaces_throws() { Short shortNum = Short.parseShort("12"); DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" 12 ", shortNum); Schema schema = Schema.builder() .addInt16Field("a_short") .addInt32Field("an_integer") ...