focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean hasAnyMethodHandlerAnnotation() { return !operationsWithHandlerAnnotation.isEmpty(); }
@Test public void testHandlerClass() { BeanInfo info = new BeanInfo(context, MyClass.class); assertTrue(info.hasAnyMethodHandlerAnnotation()); }
String getDownloadURL(double lat, double lon) { int lonInt = getMinLonForTile(lon); int latInt = getMinLatForTile(lat); String north = getNorthString(latInt); String dir; if (north.equals("N")) { dir = "North/"; if (lat >= 30) dir += "North...
@Test public void testGetDownloadUrl() { // Created a couple of random tests and compared to https://topotools.cr.usgs.gov/gmted_viewer/viewer.htm assertEquals("North/North_30_60/N42E011.hgt", instance.getDownloadURL(42.940339, 11.953125)); assertEquals("North/North_30_60/N38W078.hgt", insta...
private PythonMap( PythonCallableSource pythonFunction, Coder<?> outputCoder, String pythonTransform) { this.pythonFunction = pythonFunction; this.outputCoder = outputCoder; this.pythonTransform = pythonTransform; this.extraPackages = new ArrayList<>(); }
@Test @Category({ValidatesRunner.class, UsesPythonExpansionService.class}) public void testPythonMap() { PCollection<String> output = testPipeline .apply("CreateData", Create.of(ImmutableList.of("a", "b", "c", "d"))) .apply( "ApplyPythonMap", Pytho...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final List<Header> headers = new ArrayList<Header>(this.headers()); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status)...
@Test public void testReadCloseReleaseEntity() throws Exception { final Path test = new DAVTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); final Tran...
synchronized boolean processUpdate(FunctionMetaData updateRequestFs) throws IllegalArgumentException { log.debug("Process update request: {}", updateRequestFs); boolean needsScheduling = false; // Worker doesn't know about the function so far if (!this.containsFunctionMetaData(updateR...
@Test public void processUpdateTest() throws PulsarClientException { SchedulerManager schedulerManager = mock(SchedulerManager.class); WorkerConfig workerConfig = new WorkerConfig(); workerConfig.setWorkerId("worker-1"); FunctionMetaDataManager functionMetaDataManager = spy( ...
public BigMatrix submatrix(int i, int j, int k, int l) { if (i < 0 || i >= m || k < i || k >= m || j < 0 || j >= n || l < j || l >= n) { throw new IllegalArgumentException(String.format("Invalid submatrix range (%d:%d, %d:%d) of %d x %d", i, k, j, l, m, n)); } long offset = index(i,...
@Test public void testSubmatrix() { BigMatrix sub = matrix.submatrix(0, 1, 2, 2); System.out.println(matrix); System.out.println(sub); assertEquals(3, sub.nrow()); assertEquals(2, sub.ncol()); assertEquals(0.4, sub.get(0,0), 1E-7); assertEquals(0.8, sub.get(2,...
public static boolean bindRemotePort(Session session, int bindPort, String host, int port) throws JschRuntimeException { if (session != null && session.isConnected()) { try { session.setPortForwardingR(bindPort, host, port); } catch (JSchException e) { throw new JschRuntimeException(e, "From [{}] mappin...
@Test @Disabled public void bindRemotePort() throws InterruptedException { // 建立会话 Session session = JschUtil.getSession("looly.centos", 22, "test", "123456"); // 绑定ssh服务端8089端口到本机的8000端口上 boolean b = JschUtil.bindRemotePort(session, 8089, "localhost", 8000); assertTrue(b); // 保证一直运行 // while (true){ // ...
private Optional<BindingTableRule> findBindingTableRule(final Collection<String> logicTableNames) { for (String each : logicTableNames) { Optional<BindingTableRule> result = findBindingTableRule(each); if (result.isPresent()) { return result; } } ...
@Test void assertGetBindingTableRuleForFound() { ShardingRule actual = createMaximumShardingRule(); assertTrue(actual.findBindingTableRule("logic_Table").isPresent()); assertThat(actual.findBindingTableRule("logic_Table").get().getShardingTables().size(), is(2)); }
public static boolean fullyDeleteContents(final File dir) { return fullyDeleteContents(dir, false); }
@Test (timeout = 30000) public void testFullyDeleteContents() throws IOException { boolean ret = FileUtil.fullyDeleteContents(del); Assert.assertTrue(ret); Verify.exists(del); Assert.assertEquals(0, Objects.requireNonNull(del.listFiles()).length); validateTmpDir(); }
@Override public String named() { return PluginEnum.SPRING_CLOUD.getName(); }
@Test public void named() { final String result = springCloudPlugin.named(); assertEquals(PluginEnum.SPRING_CLOUD.getName(), result); }
public List<CredentialRetriever> asList() throws FileNotFoundException { List<CredentialRetriever> credentialRetrievers = new ArrayList<>(); if (knownCredentialRetriever != null) { credentialRetrievers.add(knownCredentialRetriever); } if (credentialHelper != null) { // If credential helper c...
@Test public void testDockerConfigRetrievers_undefinedHome() throws FileNotFoundException { List<CredentialRetriever> retrievers = new DefaultCredentialRetrievers( mockCredentialRetrieverFactory, new Properties(), new HashMap<>()) .asList(); assertThat(retrievers) ....
public static Thread daemonThread(Runnable r, Class<?> context, String description) { return daemonThread(r, "hollow", context, description); }
@Test public void nullPlatform() { try { daemonThread(() -> {}, null, getClass(), "boom"); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("platform required", e.getMessage()); } }
public Flowable<String> getKeys() { return getKeysByPattern(null); }
@Test public void testUnlinkByPattern() { RBucketRx<String> bucket = redisson.getBucket("test1"); sync(bucket.set("someValue")); RMapRx<String, String> map = redisson.getMap("test2"); sync(map.fastPut("1", "2")); Assertions.assertEquals(2, sync(redisson.getKeys().unlinkByPat...
private synchronized boolean validateClientAcknowledgement(long h) { if (h < 0) { throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h); } if (h > MASK) { throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa...
@Test public void testValidateClientAcknowledgement_rollover_edgecase_sent() throws Exception { // Setup test fixture. final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1; final long h = MAX; final long oldH = MAX - 1; final Long lastUnackedX = MAX; ...
public boolean isEnabled() { return enabled; }
@Test public void isEnabled() { assertTrue(new MapStoreConfig().isEnabled()); }
public static ParameterTool paramsFromGenericOptionsParser(String[] args) throws IOException { Option[] options = new GenericOptionsParser(args).getCommandLine().getOptions(); Map<String, String> map = new HashMap<String, String>(); for (Option option : options) { String[] split = op...
@Test void testParamsFromGenericOptionsParser() throws IOException { ParameterTool parameter = HadoopUtils.paramsFromGenericOptionsParser( new String[] {"-D", "input=myInput", "-DexpectedCount=15"}); validate(parameter); }
@Override public void doFilter(IConfigRequest request, IConfigResponse response, IConfigFilterChain filterChain) throws NacosException { if (Objects.nonNull(request) && request instanceof ConfigRequest && Objects.isNull(response)) { // Publish configuration, encrypt ...
@Test void doFilter() throws NacosException { Mockito.when(configRequest.getDataId()).thenReturn("cipher-aes-test"); Mockito.when(configRequest.getContent()).thenReturn("nacos"); configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); Mockito.verif...
public static long parseLongAscii(final CharSequence cs, final int index, final int length) { if (length <= 0) { throw new AsciiNumberFormatException("empty string: index=" + index + " length=" + length); } final boolean negative = MINUS_SIGN == cs.charAt(index); ...
@Test void parseLongAsciiRoundTrip() { final String prefix = "long to test"; final StringBuilder buffer = new StringBuilder(64); buffer.append(prefix); for (int i = 0; i < ITERATIONS; i++) { final long value = ThreadLocalRandom.current().nextLong(); ...
public Optional<GroupDto> findGroup(DbSession dbSession, String groupName) { return dbClient.groupDao().selectByName(dbSession, groupName); }
@Test public void findGroup_whenGroupExists_returnsIt() { GroupDto groupDto = mockGroupDto(); when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME)) .thenReturn(Optional.of(groupDto)); assertThat(groupService.findGroup(dbSession, GROUP_NAME)).contains(groupDto); }
@Override protected String buildHandle(final List<URIRegisterDTO> uriList, final SelectorDO selectorDO) { List<DivideUpstream> addList = buildDivideUpstreamList(uriList); List<DivideUpstream> canAddList = new CopyOnWriteArrayList<>(); boolean isEventDeleted = uriList.size() == 1 && EventType...
@Test public void testBuildHandle() { shenyuClientRegisterDivideService = spy(shenyuClientRegisterDivideService); final String returnStr = "[{protocol:'http://',upstreamHost:'localhost',upstreamUrl:'localhost:8090',warmup:10,weight:50,status:true,timestamp:1637826588267}," + "{proto...
@Override public AllocateResponse allocate(AllocateRequest allocateRequest) throws YarnException, IOException { AllocateResponse allocateResponse = null; long startTime = System.currentTimeMillis(); synchronized (this) { if(this.shutdown){ throw new YarnException("Allocate called after...
@Test public void testResendRequestsOnRMRestart() throws YarnException, IOException { ContainerId c1 = createContainerId(1); ContainerId c2 = createContainerId(2); ContainerId c3 = createContainerId(3); // Ask for two containers, one with location preference this.asks.add(createResourceRequ...
public static Builder custom() { return new Builder(); }
@Test public void buildTimeoutDurationIsNotWithinLimits() { exception.expect(ThrowableCauseMatcher.hasCause(isA(ArithmeticException.class))); exception.expectMessage("TimeoutDuration too large"); RateLimiterConfig.custom() .timeoutDuration(Duration.ofSeconds(Long.MAX_VALUE)); ...
@Override public List<ValidationMessage> validate(ValidationContext context) { return context.query().tokens().stream() .filter(this::isInvalidOperator) .map(token -> { final String errorMessage = String.format(Locale.ROOT, "Query contains invalid operator...
@Test void testLongStringOfInvalidTokens() { final ValidationContext context = TestValidationContext.create("and and and or or or") .build(); final List<ValidationMessage> messages = sut.validate(context); assertThat(messages.size()).isEqualTo(6); assertThat(messages....
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testWatermarkAddBeforeReadEndOfWindow() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.END_OF_WINDOW); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); SettableFuture<Instant> future = SettableFutu...
public SearchQuery parse(String encodedQueryString) { if (Strings.isNullOrEmpty(encodedQueryString) || "*".equals(encodedQueryString)) { return new SearchQuery(encodedQueryString); } final var queryString = URLDecoder.decode(encodedQueryString, StandardCharsets.UTF_8); fina...
@Test void explicitAllowedField() { SearchQueryParser parser = new SearchQueryParser("defaultfield", ImmutableSet.of("name", "id")); final SearchQuery query = parser.parse("name:foo"); final Multimap<String, SearchQueryParser.FieldValue> queryMap = query.getQueryMap(); assertThat(qu...
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String g...
@Test public void testExecute() throws SubCommandException { GetConsumerStatusCommand cmd = new GetConsumerStatusCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-g default-group", "-t unit-test", "-i clientid", Str...
public String join(final Stream<?> parts) { return join(parts.iterator()); }
@Test public void shouldHandleNulls() { assertThat(joiner.join(Arrays.asList("a", null, "c")), is("a, null or c")); }
public static long findAndVerifyWindowGrace(final GraphNode graphNode) { return findAndVerifyWindowGrace(graphNode, ""); }
@Test public void shouldThrowOnNull() { try { GraphGraceSearchUtil.findAndVerifyWindowGrace(null); fail("Should have thrown."); } catch (final TopologyException e) { assertThat(e.getMessage(), is("Invalid topology: Window close time is only defined for windowed co...
public BundleProcessor getProcessor( BeamFnApi.ProcessBundleDescriptor descriptor, List<RemoteInputDestination> remoteInputDesinations) { checkState( !descriptor.hasStateApiServiceDescriptor(), "The %s cannot support a %s containing a state %s.", BundleProcessor.class.getSimpleNa...
@Test public void testRegisterWithStateRequiresStateDelegator() throws Exception { ProcessBundleDescriptor descriptor = ProcessBundleDescriptor.newBuilder() .setId("test") .setStateApiServiceDescriptor(ApiServiceDescriptor.newBuilder().setUrl("foo")) .build(); List...
public static List<String> resolveCompsDependency(Service service) { List<String> components = new ArrayList<String>(); for (Component component : service.getComponents()) { int depSize = component.getDependencies().size(); if (!components.contains(component.getName())) { components.add(comp...
@Test public void testResolveCompsDependency() { Service service = createExampleApplication(); List<String> dependencies = new ArrayList<String>(); dependencies.add("compb"); Component compa = createComponent("compa"); compa.setDependencies(dependencies); Component compb = createComponent("com...
@Override public void properties(SAPropertiesFetcher saPropertiesFetcher) { // read super property JSONObject superProperties = mSensorsDataAPI.getSuperProperties(); // read dynamic property JSONObject dynamicProperty = mSensorsDataAPI.getDynamicProperty(); // merge super and...
@Test public void properties() { JSONObject superProperty = new JSONObject(); try { superProperty.put("superProperty", "superProperty"); } catch (JSONException e) { e.printStackTrace(); } SensorsDataAPI sensorsDataAPI = SAHelper.initSensors(mApplicatio...
@Override @SuppressWarnings("CallToSystemGC") public void execute(Map<String, List<String>> parameters, PrintWriter output) { final int count = parseRuns(parameters); for (int i = 0; i < count; i++) { output.println("Running GC..."); output.flush(); runtime.gc...
@Test void defaultsToOneRunIfTheQueryParamDoesNotParse() throws Exception { task.execute(Collections.singletonMap("runs", Collections.singletonList("$")), output); verify(runtime, times(1)).gc(); }
public static void copyInstances(Collection<InstanceInfo> instances, Applications result) { if (instances != null) { for (InstanceInfo instance : instances) { Application app = result.getRegisteredApplications(instance.getAppName()); if (app == null) { ...
@Test public void testCopyInstancesIfNotNullReturnCollectionOfInstanceInfo() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.copyInstances( new Array...
@Override public YamlShardingRuleConfiguration swapToYamlConfiguration(final ShardingRuleConfiguration data) { YamlShardingRuleConfiguration result = new YamlShardingRuleConfiguration(); data.getTables().forEach(each -> result.getTables().put(each.getLogicTable(), tableSwapper.swapToYamlConfiguratio...
@Test void assertSwapToYamlConfiguration() { YamlShardingRuleConfiguration actual = getSwapper().swapToYamlConfiguration(createMaximumShardingRuleConfiguration()); assertThat(actual.getTables().size(), is(2)); assertThat(actual.getAutoTables().size(), is(1)); assertThat(actual.getBin...
@Override public Xid[] recover(final int flags) throws XAException { try { return delegate.recover(flags); } catch (final XAException ex) { throw mapXAException(ex); } }
@Test void assertRecover() throws XAException { singleXAResource.recover(1); verify(xaResource).recover(1); }
@Override public ProtobufSystemInfo.Section toProtobuf() { Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Settings"); PropertyDefinitions definitions = settings.getDefinitions(); TreeMap<String, String> orderedProps = new TreeMap<>(settings.getProperties()); ordered...
@Test public void return_default_new_code_definition_with_no_specified_value() { dbTester.newCodePeriods().insert(NewCodePeriodType.PREVIOUS_VERSION,null); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Default New Code Definition", "PREVIOUS_VERSION"); }
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) throws SecurityException { return getMethod(clazz, false, methodName, paramTypes); }
@Test @Disabled public void getMethodBenchTest() { // 预热 getMethodWithReturnTypeCheck(TestBenchClass.class, false, "getH"); final TimeInterval timer = DateUtil.timer(); timer.start(); for (int i = 0; i < 100000000; i++) { ReflectUtil.getMethod(TestBenchClass.class, false, "getH"); } Console.log(time...
@Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CeTask ceTask = (CeTask) o; return uuid.equals(ceTask.uuid); }
@Test public void submitter_equals_and_hashCode_on_uuid() { CeTask.User user1 = new CeTask.User("UUID_1", null); CeTask.User user1bis = new CeTask.User("UUID_1", null); CeTask.User user2 = new CeTask.User("UUID_2", null); CeTask.User user1_diff_login = new CeTask.User("UUID_1", "LOGIN"); assertTh...
public static Type instantiateType(String solidityType, Object value) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, ClassNotFoundException { return instantiateTy...
@SuppressWarnings("unchecked") @Test public void multiDimArrays() throws Exception { byte[] bytes1d = new byte[] {1, 2, 3}; byte[][] bytes2d = new byte[][] {bytes1d, bytes1d, bytes1d}; final byte[][][] bytes3d = new byte[][][] {bytes2d, bytes2d, bytes2d}; assertEquals(TypeDecode...
@Override public boolean equals(@Nullable Object obj) { if (!(obj instanceof S3ResourceId)) { return false; } S3ResourceId o = (S3ResourceId) obj; return scheme.equals(o.scheme) && bucket.equals(o.bucket) && key.equals(o.key); }
@Test public void testEquals() { S3ResourceId a = S3ResourceId.fromComponents("s3", "bucket", "a/b/c"); S3ResourceId b = S3ResourceId.fromComponents("s3", "bucket", "a/b/c"); assertEquals(a, b); b = S3ResourceId.fromComponents("s3", a.getBucket(), "a/b/c/"); assertNotEquals(a, b); b = S3Reso...
public void validate(AlmSettingDto dto) { try { azureDevOpsHttpClient.checkPAT(requireNonNull(dto.getUrl()), requireNonNull(dto.getDecryptedPersonalAccessToken(settings.getEncryption()))); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid Azure URL or Persona...
@Test public void validate_givenHttpClientThrowingException_throwException() { AlmSettingDto dto = createMockDto(); doThrow(new IllegalArgumentException()).when(azureDevOpsHttpClient).checkPAT(any(), any()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> underTest.vali...
public static boolean setFieldValue(Object target, String fieldName, Object value) { final Optional<Field> fieldOption = getField(target, fieldName); if (!fieldOption.isPresent()) { return false; } final Field field = fieldOption.get(); if (isFinalField(field)) { ...
@Test public void setFieldValue() throws NoSuchFieldException, IllegalAccessException { final TestReflect reflect = new TestReflect(); int x = 102, y = 1899; ReflectUtils.setFieldValue(reflect, "x", x); ReflectUtils.setFieldValue(reflect, "y", y); Assert.assertEquals(reflect....
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 shouldParseSingular() { assertThat(DurationParser.parse("1 Second"), is(Duration.ofSeconds(1))); }
@VisibleForTesting void handleResponse(DiscoveryResponseData response) { ResourceType resourceType = response.getResourceType(); switch (resourceType) { case NODE: handleD2NodeResponse(response); break; case D2_URI_MAP: handleD2URIMapResponse(response); break;...
@Test public void testHandleD2URICollectionResponseWithRemoval() { DiscoveryResponseData removeClusterResponse = new DiscoveryResponseData(D2_URI, null, Collections.singletonList(CLUSTER_GLOB_COLLECTION), NONCE, null); XdsClientImplFixture fixture = new XdsClientImplFixture(); fixture._clusterS...
public static DataSchema avroToDataSchema(String avroSchemaInJson, AvroToDataSchemaTranslationOptions options) throws IllegalArgumentException { ValidationOptions validationOptions = SchemaParser.getDefaultSchemaParserValidationOptions(); validationOptions.setAvroUnionMode(true); SchemaParserFactory ...
@Test(dataProvider = "fromAvroSchemaData") public void testFromAvroSchema(String avroText, String schemaText) throws Exception { AvroToDataSchemaTranslationOptions options[] = { new AvroToDataSchemaTranslationOptions(AvroToDataSchemaTranslationMode.TRANSLATE), new AvroToDataSchemaTranslationOpti...
@Override public String retrieveIPfilePath(String id, String dstDir, Map<Path, List<String>> localizedResources) { // Assume .aocx IP file is distributed by DS to local dir String ipFilePath = null; LOG.info("Got environment: " + id + ", search IP file in localized resources"); if (null...
@Test public void testIPfileNotDefined() { Map<Path, List<String>> resources = createResources(); String path = plugin.retrieveIPfilePath(null, "workDir", resources); assertNull("Retrieved IP file path", path); }
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}") public ApolloConfig queryConfig(@PathVariable String appId, @PathVariable String clusterName, @PathVariable String namespace, @RequestParam(value = "dataCenter", required = false) String da...
@Test public void testQueryConfigForNoAppIdPlaceHolder() throws Exception { String someClientSideReleaseKey = "1"; HttpServletResponse someResponse = mock(HttpServletResponse.class); String appId = ConfigConsts.NO_APPID_PLACEHOLDER; ApolloConfig result = configController.queryConfig(appId, someCluste...
@Override @Deprecated public <VR> KStream<K, VR> transformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, ? extends VR> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransformerSup...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullNamedOnTransformValuesWithValueTransformerSupplierAndStores() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.transformValues( valueTransformer...
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void retryOnResultFailAfterMaxAttemptsUsingSingle() throws InterruptedException { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of("t...
@Override public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) { Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:" + " URI path should not be null"); if (checkOSSCredentials(conf)) { try { return OSSUnderFileSystem.createInstance(new ...
@Test public void createInstanceWithNullPath() { Exception e = Assert.assertThrows(NullPointerException.class, () -> mFactory.create( null, mConf)); Assert.assertTrue(e.getMessage().contains("Unable to create UnderFileSystem instance: URI " + "path should not be null")); }
public static void delete(final File file, final boolean ignoreFailures) { if (file.exists()) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files)...
@Test void deleteIgnoreFailuresShouldThrowExceptionIfDeleteOfADirectoryFails() { final File dir = mock(File.class); when(dir.exists()).thenReturn(true); when(dir.isDirectory()).thenReturn(true); when(dir.delete()).thenReturn(false); assertThrows(NullPointerException.clas...
@Override public void onEvent(Event event) { Set<NacosTraceSubscriber> subscribers = interestedEvents.get(event.getClass()); if (null == subscribers) { return; } TraceEvent traceEvent = (TraceEvent) event; for (NacosTraceSubscriber each : subscribers) { ...
@Test void testOnEventWithExecutor() { Executor executor = mock(Executor.class); doAnswer(invocationOnMock -> { invocationOnMock.getArgument(0, Runnable.class).run(); return null; }).when(executor).execute(any(Runnable.class)); when(mockInstanceSubscriber.exec...
@Override public boolean canPass(Node node, int acquireCount) { return canPass(node, acquireCount, false); }
@Test public void testCanPassForThreadCount() { int threshold = 8; TrafficShapingController controller = new DefaultController(threshold, RuleConstant.FLOW_GRADE_THREAD); Node node = mock(Node.class); when(node.curThreadNum()).thenReturn(threshold - 1) .thenReturn(thresho...
protected SQLStatement parseAdd() { Lexer.SavePoint mark = lexer.mark(); lexer.nextToken(); if (lexer.identifierEquals("JAR")) { lexer.nextPath(); String path = lexer.stringVal(); HiveAddJarStatement stmt = new HiveAddJarStatement(); stmt.setPath(...
@Test public void testAddJarStatement() { String s = "add jar hdfs:///hadoop/parser.h.file"; HiveStatementParser hiveStatementParser = new HiveStatementParser(s); SQLStatement sqlStatement = hiveStatementParser.parseAdd(); assertTrue(sqlStatement instanceof HiveAddJarStatement); ...
@Override public HttpAction restore(final CallContext ctx, final String defaultUrl) { val webContext = ctx.webContext(); val sessionStore = ctx.sessionStore(); val optRequestedUrl = sessionStore.get(webContext, Pac4jConstants.REQUESTED_URL); HttpAction requestedAction = null; ...
@Test public void testRestoreEmptyString() { val context = MockWebContext.create(); val sessionStore = new MockSessionStore(); sessionStore.set(context, Pac4jConstants.REQUESTED_URL, null); val action = handler.restore(new CallContext(context, sessionStore), LOGIN_URL); asser...
public PaginationContext createPaginationContext(final TopProjectionSegment topProjectionSegment, final Collection<ExpressionSegment> expressions, final List<Object> params) { Collection<AndPredicate> andPredicates = expressions.stream().flatMap(each -> ExpressionExtractUtils.getAndPredicates(each).stream()).co...
@Test void assertCreatePaginationContextWhenPredicateInRightValue() { String name = "rowNumberAlias"; ColumnSegment columnSegment = new ColumnSegment(0, 10, new IdentifierValue(name)); InExpression inExpression = new InExpression(0, 0, columnSegment, new ListExpression(0, 0), false); ...
public static void main(final String[] args) { SpringApplication.run(SimpleDemoApplication.class, args); }
@Test void checkPossibilityToSimplyStartAndRestartApplication() { this.configuration.getStorageInstance().stop(); SimpleDemoApplication.main(new String[]{}); }
public static Collection<ExternalResource> getExternalResourcesCollection( Configuration config) { return getExternalResourceAmountMap(config).entrySet().stream() .map(entry -> new ExternalResource(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); ...
@Test public void testRecognizeEmptyResourceList() { final Configuration config = new Configuration(); config.setString( ExternalResourceOptions.EXTERNAL_RESOURCE_LIST.key(), ExternalResourceOptions.NONE); config.setLong( ExternalResourceOptions.getAmountConfi...
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldNotLoadCustomUDfsIfLoadCustomUdfsFalse() { // udf in udf-example.jar try { FUNC_REG_WITHOUT_CUSTOM.getUdfFactory(FunctionName.of("tostring")); fail("Should have thrown as function doesn't exist"); } catch (final KsqlException e) { // pass } }
@Override public void configure(final Map<String, ?> config) { configure( config, new Options(), org.rocksdb.LRUCache::new, org.rocksdb.WriteBufferManager::new ); }
@Test public void shouldUseConfiguredBlockCacheSize() { KsqlBoundedMemoryRocksDBConfigSetter.configure( CONFIG_PROPS, rocksOptions, cacheFactory, bufferManagerFactory ); // Then: verify(cacheFactory).create(eq(16 * 1024 * 1024 * 1024L), anyInt(), anyBoolean(), anyDoubl...
@Override public String[] getManagedIndices() { final Set<String> indexNames = indices.getIndexNamesAndAliases(getIndexWildcard()).keySet(); // also allow restore archives to be returned final List<String> result = indexNames.stream() .filter(this::isManagedIndex) ...
@Test public void getAllGraylogIndexNames() { final Map<String, Set<String>> indexNameAliases = ImmutableMap.of( "graylog_1", Collections.emptySet(), "graylog_2", Collections.emptySet(), "graylog_3", Collections.emptySet(), "graylog_4_restored_...
public File getDatabaseFile(String filename) { File dbFile = null; if (filename != null && filename.trim().length() > 0) { dbFile = new File(filename); } if (dbFile == null || dbFile.isDirectory()) { dbFile = new File(new AndroidContextUtil().getDatabasePath("logback.db")); } return ...
@Test public void setsDatabaseFilename() throws IOException { final File tmpFile = tmp.newFile(); final File file = appender.getDatabaseFile(tmpFile.getAbsolutePath()); assertThat(file, is(notNullValue())); assertThat(file.getName(), is(tmpFile.getName())); }
public static ErrorDetail createErrorDetail(String idempotentId, String title, Exception e, boolean canSkip) { return ErrorDetail.builder() .setId(idempotentId) .setTitle(title) .setException(Throwables.getStackTraceAsString(e)) .setCanSkip(canSkip).build(); }
@Test public void test_createErrorDetail() { String id = "testId"; String title = "testTitle"; Exception exception = new IOException(); boolean canSkip = false; ErrorDetail expected = ErrorDetail.builder() .setId(id) .setTitle(title) .setException(Throwables.getStackTrace...
static JavaInput reorderModifiers(String text) throws FormatterException { return reorderModifiers( new JavaInput(text), ImmutableList.of(Range.closedOpen(0, text.length()))); }
@Test public void sealedClass() throws FormatterException { assume().that(Runtime.version().feature()).isAtLeast(16); assertThat(ModifierOrderer.reorderModifiers("non-sealed sealed public").getText()) .isEqualTo("public sealed non-sealed"); }
@ProcessElement public void processElement( @Element DataChangeRecord dataChangeRecord, OutputReceiver<DataChangeRecord> receiver) { final Instant commitInstant = new Instant(dataChangeRecord.getCommitTimestamp().toSqlTimestamp().getTime()); metrics.incDataRecordCounter(); measureCommitTime...
@Test public void testPostProcessingMetrics() { DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeMicroseconds(1L), "serverTransactionId", true, "recordSequence", "tableName", Arra...
public Stream<SqlMigration> getMigrations() { SqlMigrationProvider migrationProvider = getMigrationProvider(); try { final Map<String, SqlMigration> commonMigrations = getCommonMigrations(migrationProvider).stream().collect(toMap(SqlMigration::getFileName, m -> m)); final Map<St...
@Test void testDatabaseSpecificMigrations() { final DatabaseMigrationsProvider databaseCreator = new DatabaseMigrationsProvider(MariaDbStorageProviderStub.class); final Stream<SqlMigration> databaseSpecificMigrations = databaseCreator.getMigrations(); assertThat(databaseSpecificMigrations)....
public static String encodingParams(Map<String, String> params, String encoding) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); if (null == params || params.isEmpty()) { return null; } for (Map.Entry<String, String> entry : params.en...
@Test void testEncodingParamsMapWithNullOrEmpty() throws UnsupportedEncodingException { assertNull(HttpUtils.encodingParams((Map<String, String>) null, "UTF-8")); assertNull(HttpUtils.encodingParams(Collections.emptyMap(), "UTF-8")); }
@SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/21068) }) /* * Returns an iterables containing all distinct keys in this multimap. */ public PrefetchableIterable<K> keys() { checkState( !isClosed, "Multimap user state is no longer usable because it is clo...
@Test public void testKeys() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient( ImmutableMap.of( createMultimapKeyStateKey(), KV.of(ByteArrayCoder.of(), singletonList(A1)), createMultimapValueStateKey(A1), ...
@Override public String toString() { return String.format( "%s{leaderLatchPath='%s'}", getClass().getSimpleName(), leaderLatchPath); }
@Test void testToStringContainingLeaderLatchPath() throws Exception { new Context() { { runTest( () -> assertThat(leaderElectionDriver.toString()) .as( ...
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoun...
@Test public void shouldMakeClassesNonFinal() throws Exception { Class<?> clazz = loadClass(AFinalClass.class); assertEquals(0, clazz.getModifiers() & Modifier.FINAL); }
public int read(final MessageHandler handler) { return read(handler, Integer.MAX_VALUE); }
@Test void shouldNotReadSingleMessagePartWayThroughWriting() { final long head = 0L; final int headIndex = (int)head; when(buffer.getLong(HEAD_COUNTER_INDEX)).thenReturn(head); when(buffer.getIntVolatile(lengthOffset(headIndex))).thenReturn(0); final MutableInteger time...
public static NodeBadge number(int n) { // TODO: consider constraints, e.g. 1 <= n <= 999 return new NodeBadge(Status.INFO, false, Integer.toString(n), null); }
@Test public void numberError() { badge = NodeBadge.number(Status.ERROR, NUM); checkFields(badge, Status.ERROR, false, NUM_STR, null); }
public static String javaforLoop(String str) { StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); result.append(c); } return result.toString(); }
@Test public void whenUseJavaForLoop_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; String result = StringIterator.javaforLoop(input); assertEquals(expectedOutput, result); }
@Override public List<MetricFamilySamples> collect() { try { return exporter.export("Prometheus") .<List<MetricFamilySamples>>map(optional -> Collections.singletonList((GaugeMetricFamily) optional.getRawMetricFamilyObject())).orElse(Collections.emptyList()); // CH...
@Test void assertCollectWithPresentMetricsExporter() { MetricsExporter exporter = mock(MetricsExporter.class); when(exporter.export("Prometheus")).thenReturn(Optional.of(mock(GaugeMetricFamilyMetricsCollector.class))); assertThat(new PrometheusMetricsExporter(exporter).collect().size(), is(1...
public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException { if ((defaultManagedBean == null && customManagedBean == null) || objectName == null) return null; // skip proxy classes if (defaultManagedBean != null && P...
@Test(expected = IllegalArgumentException.class) public void testAttributeGetterNameNotCapitial() throws JMException { mbeanInfoAssembler.getMBeanInfo(new BadAttributeGetterNameNotCapital(), null, "someName"); }
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) { List<Object> valuesInOrder = schema.getFields().stream() .map( field -> { try { org.apache.avro.Schema.Field avroField = rec...
@Test public void testToBeamRow_inlineArrayNulls() { Row beamRow = BigQueryUtils.toBeamRow(ARRAY_TYPE_NULLS, BQ_INLINE_ARRAY_ROW_NULLS); assertEquals(ARRAY_ROW_NULLS, beamRow); }
public synchronized MutableQuantiles newQuantiles(String name, String desc, String sampleName, String valueName, int interval) { checkMetricName(name); if (interval <= 0) { throw new MetricsException("Interval should be positive. Value passed" + " is: " + interval); } MutableQuant...
@Test public void testAddIllegalParameters() { final MetricsRegistry r = new MetricsRegistry("IllegalParamTest"); expectMetricsException("Interval should be positive. Value passed is: -20", new Runnable() { @Override public void run() { r.newQuantiles("q1", "New Quantile 1", "q...
@Override public FilterBindings get() { return filterBindings; }
@Test void requireThatEmptyInputGivesEmptyOutput() { final FilterChainRepository filterChainRepository = new FilterChainRepository( new ChainsConfig(new ChainsConfig.Builder()), new ComponentRegistry<>(), new ComponentRegistry<>(), new Componen...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { DecimalMetaData decimalMetaData = new DecimalMetaData(columnDef.getColumnMeta()); return toDecimal(decimalMetaData, payload.readStringFixByBytes(decimalMetaData.getTotalByteLength())); }
@Test void assertDecodeNegativeNewDecimalWithLargeNumber() { columnDef = new MySQLBinlogColumnDef(MySQLBinaryColumnType.NEWDECIMAL); columnDef.setColumnMeta(32 << 8 | 6); byte[] newDecimalBytes = ByteBufUtil.decodeHexDump("7DFEFDB5CC2741EFDEBE4154FD52E7"); when(payload.readStringFixB...
public Map<String, ParamDefinition> getDefaultWorkflowParams() { return preprocessParams(defaultSystemParams); }
@Test public void testValidDefaultWorkflowParams() { assertFalse(defaultParamManager.getDefaultWorkflowParams().isEmpty()); assertNotNull(defaultParamManager.getDefaultWorkflowParams().get("TARGET_RUN_HOUR").getName()); }
@Override public boolean containsFreeSlot(AllocationID allocationId) { return freeSlots.contains(allocationId); }
@Test void testContainsFreeSlotReturnsFalseIfSlotDoesNotExist() { final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool(); assertThat(slotPool.containsFreeSlot(new AllocationID())).isFalse(); }
List<Condition> run(boolean useKRaft) { List<Condition> warnings = new ArrayList<>(); checkKafkaReplicationConfig(warnings); checkKafkaBrokersStorage(warnings); if (useKRaft) { // Additional checks done for KRaft clusters checkKRaftControllerStorage(warnings);...
@Test public void checkKafkaSingleMixedNodeIntentionalProducesNoWarning() { Kafka kafka = new KafkaBuilder(KAFKA) .editSpec() .editKafka() .withConfig(Map.of( // We want to avoid unrelated warnings ...
@Override public AppResponse process(Flow flow, CancelFlowRequest request) { if (appAuthenticator != null && "no_nfc".equals(request.getCode())) { appAuthenticator.setNfcSupport(false); } appSession.setAbortCode(request.getCode()); return new OkResponse(); }
@Test public void processReturnsOkResponseWithAppAuthenticatorAndNoNfcCode() { //given cancelFlowRequest.setCode("no_nfc"); //when AppResponse appResponse = aborted.process(mockedFlow, cancelFlowRequest); //then assertTrue(appResponse instanceof OkResponse); ...
public void setContract(@Nullable Produce contract) { this.contract = contract; setStoredContract(contract); handleContractState(); }
@Test public void cabbageContractCabbageGrowingAndCabbageDead() { final long unixNow = Instant.now().getEpochSecond(); final long expected = unixNow + 60; // Get the two allotment patches final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773); final FarmingPatch patch2 = farmingGuildPatc...
@PostMapping() @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) public Result<Boolean> publishConfig(ConfigForm configForm, HttpServletRequest request) throws NacosException { // check required field configForm.validate(); String encryptedDataKeyFinal = configForm.getEncr...
@Test void testPublishConfigWhenNameSpaceIsPublic() throws Exception { ConfigForm configForm = new ConfigForm(); configForm.setDataId(TEST_DATA_ID); configForm.setGroup(TEST_GROUP); configForm.setNamespaceId(TEST_NAMESPACE_ID_PUBLIC); configForm.setContent(TEST_CONTE...
@Override public TypeDescriptor<Set<T>> getEncodedTypeDescriptor() { return new TypeDescriptor<Set<T>>() {}.where( new TypeParameter<T>() {}, getElemCoder().getEncodedTypeDescriptor()); }
@Test public void testEncodedTypeDescriptor() throws Exception { TypeDescriptor<Set<Integer>> typeDescriptor = new TypeDescriptor<Set<Integer>>() {}; assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(typeDescriptor)); }
@Override public CEFParserResult evaluate(FunctionArgs args, EvaluationContext context) { final String cef = valueParam.required(args, context); final boolean useFullNames = useFullNamesParam.optional(args, context).orElse(false); final CEFParser parser = CEFParserFactory.create(); ...
@Test public void evaluate_returns_null_for_missing_CEF_string() throws Exception { final FunctionArgs functionArgs = new FunctionArgs(function, Collections.emptyMap()); final Message message = messageFactory.createMessage("__dummy", "__dummy", DateTime.parse("2010-07-30T16:03:25Z")); final ...
@Udf(description = "Returns the inverse (arc) cosine of an INT value") public Double acos( @UdfParameter( value = "value", description = "The value to get the inverse cosine of." ) final Integer value ) { return acos(value == null ? null : value.doubleValu...
@Test public void shouldHandleNegative() { assertThat(udf.acos(-0.43), closeTo(2.0152891037307157, 0.000000000000001)); assertThat(udf.acos(-0.5), closeTo(2.0943951023931957, 0.000000000000001)); assertThat(udf.acos(-1.0), closeTo(3.141592653589793, 0.000000000000001)); assertThat(udf.acos(-1), closeT...
@POST @Path("{noteId}") @ZeppelinApi public Response cloneNote(@PathParam("noteId") String noteId, String message) throws IOException, IllegalArgumentException { LOGGER.info("Clone note by JSON {}", message); checkIfUserCanWrite(noteId, "Insufficient privileges you cannot clone this note"); New...
@Test void testCloneNote() throws IOException { LOG.info("Running testCloneNote"); String note1Id = null; List<String> clonedNoteIds = new ArrayList<>(); String text1 = "%text clone note"; String text2 = "%text clone revision of note"; try { note1Id = notebook.createNote("note1", anonymo...
public AuthenticationRequest startAuthenticationProcess(HttpServletRequest httpRequest) throws ComponentInitializationException, MessageDecodingException, SamlValidationException, SharedServiceClientException, DienstencatalogusException, SamlSessionException { BaseHttpServletRequestXMLMessageDecoder decoder = d...
@Test //entrance public void parseAuthenticationSuccessfulEntranceForBvdTest() throws SamlSessionException, SharedServiceClientException, DienstencatalogusException, ComponentInitializationException, SamlValidationException, MessageDecodingException, SamlParseException { String samlRequest = readXMLFile(aut...
@Override public AttributedList<Path> run(final Session<?> session) throws BackgroundException { try { final AttributedList<Path> list; listener.reset(); if(this.isCached()) { list = cache.get(directory); listener.chunk(directory, list); ...
@Test public void testCacheListCanceledWithController() throws Exception { final Host host = new Host(new TestProtocol(), "localhost"); final Session<?> session = new NullSession(host) { @Override public AttributedList<Path> list(final Path directory, final ListProgressListen...
public static Schema removeFields(Schema schema, Set<String> fieldsToRemove) { List<Schema.Field> filteredFields = schema.getFields() .stream() .filter(field -> !fieldsToRemove.contains(field.name())) .map(field -> new Schema.Field(field.name(), field.schema(), field.doc(), field.defaultVal(...
@Test public void testRemoveFields() { // partitioned table test. String schemaStr = "{\"type\": \"record\",\"name\": \"testrec\",\"fields\": [ " + "{\"name\": \"timestamp\",\"type\": \"double\"},{\"name\": \"_row_key\", \"type\": \"string\"}," + "{\"name\": \"non_pii_col\", \"type\": \"string...
public static JRTClientConfigRequest createFromRaw(RawConfig config, long serverTimeout) { // TODO: Get trace from caller return JRTClientConfigRequestV3.createFromRaw(config, serverTimeout, Trace.createNew(), compressionType, getVespaVersion()); }
@Test public void testCreateFromRaw() { Class<FunctionTestConfig> clazz = FunctionTestConfig.class; final String configId = "foo"; RawConfig config = new RawConfig(new ConfigKey<>(clazz, configId), "595f44fec1e92a71d3e9e77456ba80d1"); JRTClientConfigRequest request = JRTConfigReques...
public <T> T unmarshal(XStream xs) { return (T) xs.unmarshal(newReader()); }
@Test public void testUnmarshal() throws Exception { Foo foo; try (InputStream is = XStreamDOMTest.class.getResourceAsStream("XStreamDOMTest.data1.xml")) { foo = (Foo) xs.fromXML(is); } assertEquals("test1", foo.bar.getTagName()); assertEquals("value", foo.bar.get...
@Override public RowIdLifetime getRowIdLifetime() { return null; }
@Test void assertGetRowIdLifetime() { assertNull(metaData.getRowIdLifetime()); }
public void isEqualTo(@Nullable Object expected) { standardIsEqualTo(expected); }
@SuppressWarnings("TruthIncompatibleType") // Intentional for testing purposes. @Test public void toStringsAreIdentical() { IntWrapper wrapper = new IntWrapper(); wrapper.wrapped = 5; expectFailure.whenTesting().that(5).isEqualTo(wrapper); assertFailureKeys("expected", "an instance of", "but was", "...
@Override public synchronized boolean onReportingPeriodEnd() { firstEventReceived = false; return false; }
@Test public void testOnReportingPeriodEnd() { assertTrue(strategy.onActivity(), "First call of onActivity() should return true."); assertFalse(strategy.onReportingPeriodEnd(), "onReportingPeriodEnd() should always return false."); assertTrue(strategy.onActivity(), "onActivity() should retur...
@Override public String toString() { return "MemberStateImpl{" + "address=" + address + ", uuid=" + uuid + ", cpMemberUuid=" + cpMemberUuid + ", name=" + name + ", clients=" + clients + ", mapsWithStats=" + mapsW...
@Test public void testDefaultConstructor() { MemberStateImpl memberState = new MemberStateImpl(); assertNotNull(memberState.toString()); }
public static <T extends Throwable> Optional<T> findThrowable( Throwable throwable, Class<T> searchType) { if (throwable == null || searchType == null) { return Optional.empty(); } Throwable t = throwable; while (t != null) { if (searchType.isAssignab...
@Test void testFindThrowableByType() { assertThat( ExceptionUtils.findThrowable( new RuntimeException(new IllegalStateException()), IllegalStateException.class)) .isPresent(); }
public static TraceTransferBean encoderFromContextBean(TraceContext ctx) { if (ctx == null) { return null; } //build message trace of the transferring entity content bean TraceTransferBean transferBean = new TraceTransferBean(); StringBuilder sb = new StringBuilder(25...
@Test public void testSubAfterTraceDataFormatTest() { TraceContext subAfterContext = new TraceContext(); subAfterContext.setTraceType(TraceType.SubAfter); subAfterContext.setRequestId("3455848576927"); subAfterContext.setCostTime(20); subAfterContext.setSuccess(true); ...