focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Node getLastNode() { return parent == null ? null : parent.getCurNode(); }
@Test public void testGetLastNode() { Context context = new NullContext(); CtEntry entry = new CtEntry(new StringResourceWrapper("testGetLastNode", EntryType.IN), null, context); assertNull(entry.parent); assertNull(entry.getLastNode()); Entry parentEntry = mock(E...
@Override public String[] split(String text) { if (splitContraction) { text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not"); text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not"); text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not"); f...
@Test public void testTokenizeDiacritizedWords() { System.out.println("tokenize words with diacritized chars (both composite and combining)"); String text = "The naïve résumé of Raúl Ibáñez; re\u0301sume\u0301."; String[] expResult = {"The", "naïve", "résumé", "of", "Raúl", "Ibáñez", ";", "r...
static void populateFirstLevelCache(final Map<EfestoClassKey, List<KieRuntimeService>> toPopulate) { List<KieRuntimeService> discoveredKieRuntimeServices = getDiscoveredKieRuntimeServices(); populateFirstLevelCache(discoveredKieRuntimeServices, toPopulate); }
@Test void populateFirstLevelCache() { List<KieRuntimeService> discoveredKieRuntimeServices = Arrays.asList(kieRuntimeServiceA, kieRuntimeServiceB, kieRuntimeServiceC, ...
@Override public void close(Duration timeout) { long waitTimeMs = timeout.toMillis(); if (waitTimeMs < 0) throw new IllegalArgumentException("The timeout cannot be negative."); waitTimeMs = Math.min(TimeUnit.DAYS.toMillis(365), waitTimeMs); // Limit the timeout to a year. ...
@Test @SuppressWarnings("deprecation") public void testDisableJmxReporter() { Properties props = new Properties(); props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999"); props.setProperty(AdminClientConfig.AUTO_INCLUDE_JMX_REPORTER_CONFIG, "false"); Kafk...
public <T extends AbstractMessageListenerContainer> T decorateMessageListenerContainer(T container) { Advice[] advice = prependTracingMessageContainerAdvice(container); if (advice != null) { container.setAdviceChain(advice); } return container; }
@Test void decorateSimpleMessageListenerContainer__adds_by_default() { SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(); assertThat(rabbitTracing.decorateMessageListenerContainer(listenerContainer)) .extracting("adviceChain") .asInstanceOf(array(Advice[].class...
public void succeededAppsSubmitted(long duration) { totalSucceededAppsSubmitted.add(duration); submitApplicationLatency.add(duration); }
@Test public void testSucceededAppsSubmitted() { long totalGoodBefore = metrics.getNumSucceededAppsSubmitted(); goodSubCluster.submitApplication(100); Assert.assertEquals(totalGoodBefore + 1, metrics.getNumSucceededAppsSubmitted()); Assert.assertEquals(100, metrics.getLatencySucceededAppsSu...
protected String getResourceName(String resourceName, /*@NonNull*/ Method method) { // If resource name is present in annotation, use this value. if (StringUtil.isNotBlank(resourceName)) { return resourceName; } // Parse name of target method. return MethodUtil.resolv...
@Test public void testGetResourceName() throws Exception { Method method = FooService.class.getMethod("random"); String resourceName = "someRandom"; String expectedResolvedName = FooService.class.getName() + ":random()"; assertThat(getResourceName(resourceName, method)).isEqualTo(res...
@Override public CloseableIterator<ScannerReport.LineCoverage> readComponentCoverage(int fileRef) { ensureInitialized(); return delegate.readComponentCoverage(fileRef); }
@Test public void verify_readComponentCoverage() { writer.writeComponentCoverage(COMPONENT_REF, of(COVERAGE_1, COVERAGE_2)); CloseableIterator<ScannerReport.LineCoverage> res = underTest.readComponentCoverage(COMPONENT_REF); assertThat(res).toIterable().containsExactly(COVERAGE_1, COVERAGE_2); res.cl...
public static Optional<String> encrypt(String publicKey, String text) { try { Cipher cipher = Cipher.getInstance(RSA_PADDING); byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey.getBytes(DEFAULT_ENCODE)); X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(pu...
@Test void encrypt() { Optional<String[]> optional = RsaUtil.generateKey(); Assertions.assertTrue(optional.isPresent()); String[] key = optional.get(); Optional<String> encryptTextOptional = RsaUtil.encrypt(key[1], TEXT); Optional<String> decryptTextOptional = RsaUtil.decrypt...
@Override public void write(final MySQLPacketPayload payload, final Object value) { LocalDateTime dateTime = value instanceof LocalDateTime ? (LocalDateTime) value : new Timestamp(((Date) value).getTime()).toLocalDateTime(); int year = dateTime.getYear(); int month = dateTime.getMonthValue()...
@Test void assertWriteLocalDateTimeTypeFourBytes() { MySQLDateBinaryProtocolValue actual = new MySQLDateBinaryProtocolValue(); actual.write(payload, LocalDateTime.of(1970, 1, 14, 0, 0, 0)); verify(payload).writeInt1(4); verify(payload).writeInt2(1970); verify(payload).writeIn...
@VisibleForTesting protected int sizeIncrement(String partitionKey, @Nullable String hashKey, byte[] record) { final int[] size = {0, 0}; // wrapper & record sizeIncrementOfKey(size, partitionKey, partitionKeys); // partition key encoding if (hashKey != null) { sizeIncrementOfKey(size, hashKey, expl...
@Test public void testSizeIncrement() { Random rnd = new Random(); List<String> keys = Stream.generate(() -> randomAscii(1, 256)).limit(3).collect(toList()); List<String> hashKeys = Stream.generate(() -> randomNumeric(1, 38)).limit(3).collect(toList()); hashKeys.add(null); int sizeBytes = BASE_OV...
@Override public boolean canRenameTo( FileObject newfile ) { return resolvedFileObject.canRenameTo( newfile ); }
@Test public void testDelegatesCanRenameTo() { FileObject newFile = mock( FileObject.class ); when( resolvedFileObject.canRenameTo( newFile ) ).thenReturn( true ); assertTrue( fileObject.canRenameTo( newFile ) ); when( resolvedFileObject.canRenameTo( newFile ) ).thenReturn( false ); assertFal...
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test public void testCreateRegisteredSchema() { p.getSchemaRegistry() .registerSchemaForClass( String.class, STRING_SCHEMA, s -> Row.withSchema(STRING_SCHEMA).addValue(s).build(), r -> r.getString("field")); PCollection<String> out = p.apply(Create.of("...
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testReplace() { run( "def text = 'words that need to be {replaced}'", "replace text.{replaced} = 'correct'", "match text == 'words that need to be correct'", "match text.toString() == 'words that need to be correct'" ); ...
@Udf public Map<String, String> splitToMap( @UdfParameter( description = "Separator string and values to join") final String input, @UdfParameter( description = "Separator string and values to join") final String entryDelimiter, @UdfParameter( description = "Separator s...
@Test public void shouldSplitStringGivenMultiCharDelimiters() { Map<String, String> result = udf.splitToMap("foo:=apple||bar:=cherry", "||", ":="); assertThat(result, hasEntry("foo", "apple")); assertThat(result, hasEntry("bar", "cherry")); assertThat(result.size(), equalTo(2)); }
public PushOffsetVector mergeCopy(final OffsetVector other) { final PushOffsetVector copy = copy(); copy.merge(other); return copy; }
@Test public void shouldMerge() { // Given: PushOffsetVector pushOffsetVector1 = new PushOffsetVector(ImmutableList.of(1L, 2L, 3L)); PushOffsetVector pushOffsetVector2 = new PushOffsetVector(ImmutableList.of(2L, 0L, 9L)); // Then: assertThat(pushOffsetVector1.mergeCopy(pushOffsetVector2), ...
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) { IdentityProvider provider = resolveProviderOrHandleResponse(request, response, CALLBACK_PATH); if (provider != null) { handleProvider(request, response, provider); } }
@Test public void do_filter_with_context_no_log_if_provider_did_not_call_authenticate_on_context() { when(request.getContextPath()).thenReturn("/sonarqube"); when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY); FakeOAuth2IdentityProvider identityProvider = new Fak...
public FEELFnResult<List<Object>> invoke( @ParameterName( "list" ) List list, @ParameterName( "item" ) Object[] items ) { return invoke((Object) list, items); }
@Test void invokeAppendSomething() { FunctionTestUtil.assertResultList(appendFunction.invoke(Collections.emptyList(), new Object[]{"test"}), List.of("test")); FunctionTestUtil.assertResultList(appendFunction.invoke(List.of("test"), new Object[]{"test2"}), ...
@Override public String convertTaskConfigToJson(TaskConfig taskConfig) { return new Gson().toJson(configPropertiesAsMap(taskConfig)); }
@Test public void shouldConvertTaskConfigObjectToJson() { TaskConfig taskConfig = new TaskConfig(); TaskConfigProperty p1 = new TaskConfigProperty("k1", "value1"); p1.with(Property.SECURE, true); p1.with(Property.REQUIRED, true); TaskConfigProperty p2 = new TaskConfigPropert...
public static RestSettingBuilder get(final String id) { return get(eq(checkId(id))); }
@Test public void should_reply_404_for_unknown_resource() throws Exception { server.resource("targets", get("2").response(with(text("hello")))); running(server, () -> { HttpResponse response = helper.getResponse(remoteUrl("/targets/1")); assertThat(response.getCode(), is(404...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void unpinAllForumTopicMessages() { String name = "edit_thread-" + System.currentTimeMillis(); BaseResponse response = bot.execute(new EditForumTopic(forum, forumEditThread, name, "")); assertTrue(response.isOk()); response = bot.execute(new UnpinAllForumTopicMessages(fo...
@Override public String toString() { return key + "=" + getValue(); }
@Test public void string() { assertThat(entry.toString()).isEqualTo(Map.entry(1, 2).toString()); }
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (paddi...
@Test public void shouldAppendPartialPaddingBytes() { final ByteBuffer result = udf.lpad(BYTES_123, 4, BYTES_45); assertThat(BytesUtils.getByteArray(result), is(new byte[]{4,1,2,3})); }
@Override public Host getHost(HostName hostName) throws HostNameNotFoundException { ApplicationInstance applicationInstance = serviceMonitor .getApplicationNarrowedTo(hostName) .orElseThrow(() -> new HostNameNotFoundException(hostName)); List<ServiceInstance> service...
@Test public void testGetHost() { ClusterControllerClientFactory clusterControllerClientFactory = new ClusterControllerClientFactoryMock(); StatusService statusService = new ZkStatusService( new MockCurator(), mock(Metric.class), new TestTimer(), ...
Timer.Context getTimerContextFromExchange(Exchange exchange, String propertyName) { return exchange.getProperty(propertyName, Timer.Context.class); }
@Test public void testGetTimerContextFromExchangeNotFound() { when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null); assertThat(producer.getTimerContextFromExchange(exchange, PROPERTY_NAME), is(nullValue())); inOrder.verify(exchange, times(1)).getProperty(PROPERTY_N...
@Override public int length() { return 2; }
@Test public void testLength() { System.out.println("length"); WeibullDistribution instance = new WeibullDistribution(1.5, 1.0); instance.rand(); assertEquals(2, instance.length()); }
@Override public void set(V value) { get(setAsync(value)); }
@Test public void testOptions() { Config c = createConfig(); c.useSingleServer().setTimeout(10); RedissonClient r = Redisson.create(c); String val = RandomString.make(1048 * 10000); Assertions.assertThrows(RedisResponseTimeoutException.class, () -> { RBucket<Str...
public boolean isNewerThan(JavaSpecVersion otherVersion) { return this.compareTo(otherVersion) > 0; }
@Test public void test8newerThan7() throws Exception { // Setup fixture. final JavaSpecVersion seven = new JavaSpecVersion( "1.7" ); final JavaSpecVersion eight = new JavaSpecVersion( "1.8" ); // Execute system under test. final boolean result = eight.isNewerThan( seven ...
public static Object convert(final Object o) { if (o == null) { return RubyUtil.RUBY.getNil(); } final Class<?> cls = o.getClass(); final Valuefier.Converter converter = CONVERTER_MAP.get(cls); if (converter != null) { return converter.convert(o); ...
@Test public void testConcreteJavaProxy() { List<IRubyObject> array = new ArrayList<>(); array.add(RubyString.newString(RubyUtil.RUBY, "foo")); RubyClass proxyClass = (RubyClass) Java.getProxyClass(RubyUtil.RUBY, ArrayList.class); ConcreteJavaProxy cjp = new ConcreteJavaProxy(RubyUti...
void allocateCollectionField( Object object, BeanInjectionInfo beanInjectionInfo, String fieldName ) { BeanInjectionInfo.Property property = getProperty( beanInjectionInfo, fieldName ); String groupName = ( property != null ) ? property.getGroupName() : null; if ( groupName == null ) { return; }...
@Test public void allocateCollectionField_Property_List_IntiallyNull() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); MetaBeanLevel1 mbl1 = new MetaBeanLevel1(); mbl1.setSub( new MetaBeanLevel2() ); BeanInjectionInfo.Property lis...
public Builder toBuilder() { return new Builder(this); }
@Test void toBuilder() { MessagingTracing messagingTracing = MessagingTracing.newBuilder(tracing).build(); assertThat(messagingTracing.toBuilder().build()) .usingRecursiveComparison() .isEqualTo(messagingTracing); assertThat(messagingTracing.toBuilder().producerSampler(neverSample()).build()) ...
public static <T> boolean isNullOrEmpty(Collection<T> collection) { if (collection == null) return true; return collection.isEmpty(); }
@Test void isNullOrEmptyIsTrueForEmptyCollection() { assertThat(isNullOrEmpty(new ArrayList<>())).isTrue(); }
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_parse_ansi_colors() { properties.put(Constants.ANSI_COLORS_DISABLED_PROPERTY_NAME, "true"); RuntimeOptions options = cucumberPropertiesParser.parse(properties).build(); assertThat(options.isMonochrome(), equalTo(true)); }
@Override public List<?> deserialize(final String topic, final byte[] bytes) { if (bytes == null) { return null; } try { final String recordCsvString = new String(bytes, StandardCharsets.UTF_8); final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat) .ge...
@Test public void shouldDeserializeNegativeDecimalSerializedAsString() { // Given: final PersistenceSchema schema = persistenceSchema( column("cost", SqlTypes.decimal(4, 2)) ); final KsqlDelimitedDeserializer deserializer = createDeserializer(schema); final byte[] bytes = "\"-01....
@Override public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { return memoryLimiter.acquire(e, timeout, unit) && super.offer(e, timeout, unit); }
@Test public void testOfferWhenTimeout() throws InterruptedException { MemoryLimitedLinkedBlockingQueue<Runnable> queue = new MemoryLimitedLinkedBlockingQueue<>(1, instrumentation); assertFalse(queue.offer(() -> { }, 2, TimeUnit.SECONDS)); }
@ApiOperation(value = "List of process definitions", tags = { "Process Definitions" }, nickname = "listProcessDefinitions") @ApiImplicitParams({ @ApiImplicitParam(name = "version", dataType = "integer", value = "Only return process definitions with the given version.", paramType = "query"), ...
@Test public void testGetProcessDefinitions() throws Exception { try { Deployment firstDeployment = repositoryService.createDeployment() .name("Deployment 1") .parentDeploymentId("parent1") .addClasspathResource("org/flowable/rest/serv...
public static String from(Path path) { return from(path.toString()); }
@Test void testUnknownContentType() { assertThatThrownBy(() -> ContentType.from(Path.of("un.known"))).isInstanceOf(IllegalArgumentException.class); }
@ScalarOperator(EQUAL) @SqlType(StandardTypes.BOOLEAN) @SqlNullable public static Boolean equal(@SqlType(StandardTypes.BOOLEAN) boolean left, @SqlType(StandardTypes.BOOLEAN) boolean right) { return left == right; }
@Test public void testEqual() { assertFunction("true = true", BOOLEAN, true); assertFunction("true = false", BOOLEAN, false); assertFunction("false = true", BOOLEAN, false); assertFunction("false = false", BOOLEAN, true); }
@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 testAddToClusterNodeLabelsWithExclusivitySetting() throws Exception { // Parenthese not match String[] args = new String[] { "-addToClusterNodeLabels", "x(" }; assertTrue(0 != rmAdminCLI.run(args)); args = new String[] { "-addToClusterNodeLabels", "x)" }; assertTrue(0 != r...
public static <T> Flattened<T> flattenedSchema() { return new AutoValue_Select_Flattened.Builder<T>() .setNameFn(CONCAT_FIELD_NAMES) .setNameOverrides(Collections.emptyMap()) .build(); }
@Test @Category(NeedsRunner.class) public void testFlattenWithOutputSchema() { List<Row> bottomRow = IntStream.rangeClosed(0, 2) .mapToObj(i -> Row.withSchema(SIMPLE_SCHEMA).addValues(i, Integer.toString(i)).build()) .collect(Collectors.toList()); List<Row> rows = bot...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthGetCompilers() throws Exception { web3j.ethGetCompilers().send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCompilers\"," + "\"params\":[],\"id\":1}"); }
public static Class<?> loadClass(String name) throws UtilException { return loadClass(name, true); }
@Test public void loadClassTest() { String name = ClassLoaderUtil.loadClass("java.lang.Thread.State").getName(); assertEquals("java.lang.Thread$State", name); name = ClassLoaderUtil.loadClass("java.lang.Thread$State").getName(); assertEquals("java.lang.Thread$State", name); }
public static boolean checkLiteralOverflowInDecimalStyle(BigDecimal value, ScalarType scalarType) { int realPrecision = getRealPrecision(value); int realScale = getRealScale(value); BigInteger underlyingInt = value.setScale(scalarType.getScalarScale(), RoundingMode.HALF_UP).unscaledValue(); ...
@Test public void testCheckLiteralOverflowInDecimalStyleSuccess() throws AnalysisException { BigDecimal decimal32Values[] = { new BigDecimal("99999.99994"), new BigDecimal("99999.9999"), new BigDecimal("99999.999"), new BigDecimal("-99999.99994...
public Span nextSpan(Message message) { TraceContextOrSamplingFlags extracted = extractAndClearTraceIdProperties(processorExtractor, message, message); Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler. // When an upstream context was not present, lookup keys are unl...
@Test void nextSpan_should_retain_baggage_headers() throws JMSException { message.setStringProperty(BAGGAGE_FIELD_KEY, ""); jmsTracing.nextSpan(message); assertThat(message.getStringProperty(BAGGAGE_FIELD_KEY)).isEmpty(); }
public FEELFnResult<List> invoke(@ParameterName( "list" ) Object list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } // spec requires us to return a new list final List<Object> result = new ArrayLi...
@Test void invokeParamCollection() { FunctionTestUtil.assertResult(flattenFunction.invoke(Arrays.asList("test", 1, 2)), Arrays.asList("test", 1, 2)); FunctionTestUtil.assertResult(flattenFunction.invoke(Arrays.asList("test", 1, 2, Arrays.asList(3, 4))), Arrays.a...
@Override public GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request) throws YarnException, IOException { if (request == null || request.getQueueName() == null) { routerMetrics.incrGetQueueInfoFailedRetrieved(); String msg = "Missing getQueueInfo request or queueName."; RouterAud...
@Test public void testSubClusterGetQueueInfo() throws IOException, YarnException { // We have set up a unit test where we access queue information for subcluster1. GetQueueInfoResponse response = interceptor.getQueueInfo( GetQueueInfoRequest.newInstance("root", true, true, true, "1")); Assert.asse...
@Override public NearCacheStats getNearCacheStats() { throw new UnsupportedOperationException("Replicated map has no Near Cache!"); }
@Test(expected = UnsupportedOperationException.class) public void testNearCacheStats() { localReplicatedMapStats.getNearCacheStats(); }
public static FinishedTriggersBitSet emptyWithCapacity(int capacity) { return new FinishedTriggersBitSet(new BitSet(capacity)); }
@Test public void testSetGet() { FinishedTriggersProperties.verifyGetAfterSet(FinishedTriggersBitSet.emptyWithCapacity(1)); }
@Override public synchronized List<ApplicationAttemptId> getAppsInQueue(String queueName) { if (queueName.equals(DEFAULT_QUEUE.getQueueName())) { List<ApplicationAttemptId> attempts = new ArrayList<ApplicationAttemptId>(applications.size()); for (SchedulerApplication<FifoAppAttempt> ap...
@Test public void testGetAppsInQueue() throws Exception { Application application_0 = new Application("user_0", resourceManager); application_0.submit(); Application application_1 = new Application("user_0", resourceManager); application_1.submit(); ResourceScheduler scheduler = resource...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testShhGetFilterChanges() throws Exception { web3j.shhGetFilterChanges(Numeric.toBigInt("0x7")).send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"shh_getFilterChanges\"," + "\"params\":[\"0x7\"],\"id\":1}"); }
public SchemaRegistryClient get() { if (schemaRegistryUrl.equals("")) { return new DefaultSchemaRegistryClient(); } final RestService restService = serviceSupplier.get(); // This call sets a default sslSocketFactory. final SchemaRegistryClient client = schemaRegistryClientFactory.create( ...
@Test public void shouldPassBasicAuthCredentialsToSchemaRegistryClient() { // Given final Map<String, Object> schemaRegistryClientConfigs = ImmutableMap.of( "ksql.schema.registry.basic.auth.credentials.source", "USER_INFO", "ksql.schema.registry.basic.auth.user.info", "username:password", ...
@Override public ParSeqBasedCompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) { return produceEitherStageAsync("applyEitherAsync", other, (t) -> { action.accept(t); return null; }, executor); }
@Test public void testAcceptEitherAsync() throws Exception { Consumer<String> consumer = mock(Consumer.class); CountDownLatch waitLatch = new CountDownLatch(1); CompletionStage<String> completionStage = createTestStage(TESTVALUE1); CompletionStage<String> completionStage2 = createTestStage(TESTVALU...
List<?> apply( final GenericRow row, final ProcessingLogger processingLogger ) { final Object[] args = new Object[parameterExtractors.size()]; for (int i = 0; i < parameterExtractors.size(); i++) { args[i] = evalParam(row, processingLogger, i); } try { final List<?> result = ...
@Test public void shouldReturnEmptyListIfUdtfThrows() { // Given: final RuntimeException e = new RuntimeException("Boom"); when(tableFunction.apply(any())).thenThrow(e); // When: final List<?> result = applier.apply(VALUE, processingLogger); // Then: assertThat(result, is(empty())); }
void prepare(Map<String, Object> conf, IMetricsContext metrics, int partitionIndex, int numPartitions) { this.options.prepare(conf, partitionIndex, numPartitions); initLastTxn(conf, partitionIndex); }
@Test public void testPrepare() { HdfsState state = createHdfsState(); Collection<File> files = FileUtils.listFiles(new File(TEST_OUT_DIR), null, false); File hdfsDataFile = Paths.get(TEST_OUT_DIR, FILE_NAME_PREFIX + "0").toFile(); assertTrue(files.contains(hdfsDataFile)); }
public static WindowStoreIterator<ValueAndTimestamp<GenericRow>> fetch( final ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> store, final GenericKey key, final Instant lower, final Instant upper ) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWi...
@Test public void shouldCallUnderlyingStoreSingleKey() throws IllegalAccessException { when(provider.stores(any(), any())).thenReturn(ImmutableList.of(meteredWindowStore)); SERDES_FIELD.set(meteredWindowStore, serdes); when(serdes.rawKey(any())).thenReturn(BYTES); when(meteredWindowStore.wrapped()).th...
public List<Favorite> search(String userId, String appId, Pageable page) { boolean isUserIdEmpty = Strings.isNullOrEmpty(userId); boolean isAppIdEmpty = Strings.isNullOrEmpty(appId); if (isAppIdEmpty && isUserIdEmpty) { throw new BadRequestException("user id and app id can't be empty at the same time...
@Test @Sql(scripts = "/sql/favorites/favorites.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testSearchByUserId() { List<Favorite> favorites = favoriteService.search(testUser, null, PageReques...
@Override public void collect(long elapsedTime, StatementContext ctx) { final Timer timer = getTimer(ctx); timer.update(elapsedTime, TimeUnit.NANOSECONDS); }
@Test public void updatesTimerForRawSql() throws Exception { final StatementNameStrategy strategy = new SmartNameStrategy(); final InstrumentedTimingCollector collector = new InstrumentedTimingCollector(registry, s...
@Override public Committer closeForCommit() throws IOException { lock(); try { uploadCurrentPart(); return upload.getCommitter(); } finally { unlock(); } }
@Test(expected = IOException.class) public void testCloseForCommitOnClosedStreamShouldFail() throws IOException { fsDataOutputStream.closeForCommit().commit(); fsDataOutputStream.closeForCommit().commit(); }
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execut...
@Test public void shouldExecuteInsertIntoWithCustomQueryId() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); // Given: KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create stream bar as select * from orders;", ksqlConfig, Collections.emptyMap(...
public void createPlainAccessConfig(final String addr, final PlainAccessConfig plainAccessConfig, final long timeoutMillis) throws RemotingException, InterruptedException, MQClientException { CreateAccessConfigRequestHeader requestHeader = new CreateAccessConfigRequestHeader(); requestHe...
@Test public void testCreatePlainAccessConfig_Success() throws InterruptedException, RemotingException { doAnswer(mock -> { RemotingCommand request = mock.getArgument(1); return createSuccessResponse4UpdateAclConfig(request); }).when(remotingClient).invokeSync(anyString(), an...
public static List<SubscriptionItem> readFrom( final InputStream in, @Nullable final ImportExportEventListener eventListener) throws InvalidSourceException { if (in == null) { throw new InvalidSourceException("input is null"); } final List<SubscriptionItem> c...
@Test public void testInvalidSource() { final List<String> invalidList = Arrays.asList( "{}", "", null, "gibberish"); for (final String invalidContent : invalidList) { try { if (invalidContent != null) { ...
@Override public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(HttpConstants.AUTHORIZATION_HEADER); if (authorizati...
@Test(timeout = 60000) public void testRequestWithoutAuthorization() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Assert.assertNull(handler.authenticate(request, response)); Mockito.veri...
public static List<String> getServerIdentities(X509Certificate x509Certificate) { List<String> names = new ArrayList<>(); for (CertificateIdentityMapping mapping : serverCertMapping) { List<String> identities = mapping.mapIdentity(x509Certificate); Log.debug("Certificate...
@Test public void testServerIdentitiesXmppAddr() throws Exception { // Setup fixture. final String subjectCommonName = "MySubjectCommonName"; final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr"; final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilde...
public Single<Boolean> addAll(Publisher<? extends V> c) { return new PublisherAdder<V>() { @Override public RFuture<Boolean> add(Object o) { return instance.addAsync((V) o); } }.addAll(c); }
@Test public void testAddAllIndexError() { Assertions.assertThrows(RedisException.class, () -> { RListRx<Integer> list = redisson.getList("list"); sync(list.addAll(2, Arrays.asList(7, 8, 9))); }); }
@Nonnull public <T> T getInstance(@Nonnull Class<T> type) { return getInstance(new Key<>(type)); }
@Test public void shouldInjectByNamedKeys() throws Exception { injector = builder .bind(new Injector.Key<>(String.class, "namedThing"), "named value") .bind(String.class, "unnamed value") .build(); NamedParams namedParams = injector.getInstance(NamedParams.class); ...
public DataSource<T> loadDataSource(Path csvPath, String responseName) throws IOException { return loadDataSource(csvPath, Collections.singleton(responseName)); }
@Test public void testInvalidResponseName() { URL path = CSVLoader.class.getResource("/org/tribuo/data/csv/test.csv"); CSVLoader<MockOutput> loader = new CSVLoader<>(new MockOutputFactory()); assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, "")); assertT...
public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } }
@Test public void isPresent() { assertThat(Optional.of("foo")).isPresent(); }
@Override public V takeLastAndOfferFirstTo(String queueName) throws InterruptedException { return commandExecutor.getInterrupted(takeLastAndOfferFirstToAsync(queueName)); }
@Test public void testTakeLastAndOfferFirstTo() throws InterruptedException { final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("{queue}1"); queue1.trySetCapacity(10); Executors.newSingleThreadScheduledExecutor().schedule(() -> { try { ...
@Override public DenseMatrix matrixMultiply(Matrix other) { if (dim2 == other.getDimension1Size()) { if (other instanceof DenseMatrix) { DenseMatrix otherDense = (DenseMatrix) other; double[][] output = new double[dim1][otherDense.dim2]; for (int ...
@Test public void matrixMatrixOtherTransposeTest() { //4x4 matrices DenseMatrix a = generateA(); DenseMatrix b = generateB(); DenseMatrix c = generateC(); DenseMatrix aaT = generateAAT(); assertEquals(aaT,a.matrixMultiply(a,false,true)); DenseMatrix abT = gen...
@Operation(summary = "getTasksByDefinitionCode", description = "GET_TASK_LIST_BY_DEFINITION_CODE_NOTES") @Parameters({ @Parameter(name = "code", description = "PROCESS_DEFINITION_CODE", required = true, schema = @Schema(implementation = long.class, example = "100")) }) @GetMapping(value = "/{cod...
@Test public void testGetNodeListByDefinitionId() { long projectCode = 1L; Long code = 1L; Map<String, Object> result = new HashMap<>(); putMsg(result, Status.SUCCESS); Mockito.when(processDefinitionService.getTaskNodeListByDefinitionCode(user, projectCode, code)) ...
@VisibleForTesting static boolean validate(TableConfig tableConfig) { String taskType = MinionConstants.UpsertCompactionTask.TASK_TYPE; String tableNameWithType = tableConfig.getTableName(); if (tableConfig.getTableType() == TableType.OFFLINE) { LOGGER.warn("Skip generation task: {} for table: {}, o...
@Test public void testValidate() { TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).setTimeColumnName(TIME_COLUMN_NAME) .build(); assertFalse(UpsertCompactionTaskGenerator.validate(tableConfig)); TableConfigBuilder tableConfigBuilder = ...
public static String addLengthPrefixedCoder( String coderId, RunnerApi.Components.Builder components, boolean replaceWithByteArrayCoder) { String lengthPrefixedByteArrayCoderId = addLengthPrefixByteArrayCoder(components); String urn = components.getCodersOrThrow(coderId).getSpec().getUrn(); // We han...
@Test public void test() throws IOException { SdkComponents sdkComponents = SdkComponents.create(); sdkComponents.registerEnvironment(Environments.createDockerEnvironment("java")); String coderId = sdkComponents.registerCoder(original); Components.Builder components = sdkComponents.toComponents().toBu...
@Override public PageResult<SmsLogDO> getSmsLogPage(SmsLogPageReqVO pageReqVO) { return smsLogMapper.selectPage(pageReqVO); }
@Test public void testGetSmsLogPage() { // mock 数据 SmsLogDO dbSmsLog = randomSmsLogDO(o -> { // 等会查询到 o.setChannelId(1L); o.setTemplateId(10L); o.setMobile("15601691300"); o.setSendStatus(SmsSendStatusEnum.INIT.getStatus()); o.setSendTime(buildTim...
public static void waitAll(CompletableFuture<?>... tasks) { try { CompletableFuture.allOf(tasks).get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } }
@Test @Disabled public void waitAndGetTest() { CompletableFuture<String> hutool = CompletableFuture.supplyAsync(() -> { ThreadUtil.sleep(1, TimeUnit.SECONDS); return "hutool"; }); CompletableFuture<String> sweater = CompletableFuture.supplyAsync(() -> { ThreadUtil.sleep(2, TimeUnit.SECONDS); return ...
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) { Objects.requireNonNull(metric); if (batchMeasure == null) { return Optional.empty(); } Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder(); switch (metric.getType().getValueType()) { ...
@Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testOrderByWithWildcard() { // TODO: validate output analyze("SELECT t1.* FROM t1 ORDER BY a"); }
@Override public int hashCode() { return ((key.hashCode() + (from != null ? from.hashCode() : 0)) * 31 + (to != null ? to.hashCode() : 0)) * 31; }
@Test void requireThatHashCodeIsImplemented() { assertEquals(new FeatureRange("key").hashCode(), new FeatureRange("key").hashCode()); }
public static Builder builder() { return new Builder(); }
@Test public void testEquals() { FilteredConnectPoint cp = new FilteredConnectPoint(NetTestTools.connectPoint("d", 1)); TransportEndpointDescription ted1 = TransportEndpointDescription .builder() .withEnabled(true) ...
public <ConfigType extends ConfigInstance> ConfigType toInstance(Class<ConfigType> clazz, String configId) { return ConfigInstanceUtil.getNewInstance(clazz, configId, this); }
@Test public void non_existent_map_of_struct_in_payload_is_ignored() { Slime slime = new Slime(); Cursor map = slime.setObject().setObject("non_existent_inner_map"); map.setObject("one").setLong("foo", 1); MaptypesConfig config = new ConfigPayload(slime).toInstance(MaptypesConfig.cla...
@Override public TopicConsumerBuilder<T> priorityLevel(int priorityLevel) { checkArgument(priorityLevel >= 0, "priorityLevel needs to be >= 0"); topicConf.setPriorityLevel(priorityLevel); return this; }
@Test public void testValidPriorityLevel() { topicConsumerBuilderImpl.priorityLevel(0); verify(topicConsumerConfigurationData).setPriorityLevel(0); }
public IndexConfig setAttributes(List<String> attributes) { checkNotNull(attributes, "Index attributes cannot be null."); this.attributes = new ArrayList<>(attributes.size()); for (String attribute : attributes) { addAttribute(attribute); } return this; }
@Test(expected = NullPointerException.class) public void testAttributesNull() { new IndexConfig().setAttributes(null); }
public MaterialAgent createAgent(MaterialRevision revision) { Material material = revision.getMaterial(); if (material instanceof DependencyMaterial) { return MaterialAgent.NO_OP; } else if (material instanceof PackageMaterial) { return MaterialAgent.NO_OP; } else...
@Test public void shouldCreateMaterialAgent_withAgentsUuidAsSubprocessExecutionContextNamespace() throws IOException { String agentUuid = "uuid-01783738"; MaterialAgentFactory factory = new MaterialAgentFactory(new InMemoryStreamConsumer(), tempWorkingDirectory, new AgentIdentifier("...
public static void deleteDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); deleteDirectoryImpl(directory.toPath()); }
@Test public void deleteDirectory_throws_IOE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); assertThatThrownBy(() -> FileUtils.deleteDirectory(file)) .isInstanceOf(IOException.class) .hasMessage("Directory '" + file.getAbsolutePath() + "' is a file"); }
public void checkIfAnyComponentsNeedIssueSync(DbSession dbSession, List<String> componentKeys) { boolean isAppOrViewOrSubview = dbClient.componentDao().existAnyOfComponentsWithQualifiers(dbSession, componentKeys, APP_VIEW_OR_SUBVIEW); boolean needIssueSync; if (isAppOrViewOrSubview) { needIssueSync = ...
@Test public void checkIfAnyComponentsNeedIssueSync_single_view_subview_or_app() { ProjectData projectData1 = insertProjectWithBranches(true, 0); ComponentDto app = db.components().insertPublicApplication().getMainBranchComponent(); ComponentDto view = db.components().insertPrivatePortfolio(); Compon...
@Override public MergedResult decorate(final QueryResult queryResult, final SQLStatementContext sqlStatementContext, final EncryptRule rule) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof MySQLExplainStatement || sqlStatement instanceof MySQLShowColu...
@Test void assertMergedResultWithShowColumnsStatement() { sqlStatementContext = getShowColumnsStatementContext(); EncryptDALResultDecorator encryptDALResultDecorator = new EncryptDALResultDecorator(mock(RuleMetaData.class)); assertThat(encryptDALResultDecorator.decorate(mock(QueryResult.clas...
@Override public boolean match(Message msg, StreamRule rule) { if(msg.getField(Message.FIELD_GL2_SOURCE_INPUT) == null) { return rule.getInverted(); } final String value = msg.getField(Message.FIELD_GL2_SOURCE_INPUT).toString(); return rule.getInverted() ^ value.trim().equal...
@Test public void testUnsuccessfulMatch() { StreamRule rule = getSampleRule(); rule.setValue("input-id-dead"); Message msg = getSampleMessage(); msg.addField(Message.FIELD_GL2_SOURCE_INPUT, "input-id-beef"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(...
public Optional<Details> restartForeachInstance( RunRequest request, WorkflowInstance instance, String foreachStepId, long restartRunId) { request.updateForDownstreamIfNeeded(foreachStepId, instance); workflowHelper.updateWorkflowInstance(instance, request); instance.setWorkflowRunId(restartRunId); ...
@Test public void testRestartForeachInstance() { doNothing().when(workflowHelper).updateWorkflowInstance(any(), any()); instance.setWorkflowId("maestro_foreach_x"); RestartConfig restartConfig = RestartConfig.builder() .restartPolicy(RunPolicy.RESTART_FROM_INCOMPLETE) .down...
@Override public long addedCount() { return tail; }
@Test public void testAddedCount() { assertEquals(0, queue.addedCount()); queue.offer(1); assertEquals(1, queue.addedCount()); }
@Override public String toString() { return data.toString(); }
@Test public void testToString() { List<StopReplicaPartitionError> errors = new ArrayList<>(); errors.add(new StopReplicaPartitionError().setTopicName("foo").setPartitionIndex(0)); errors.add(new StopReplicaPartitionError().setTopicName("foo").setPartitionIndex(1) .setErrorCode(E...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final Storage.Buckets.Get request ...
@Test public void testFindCommonPrefix() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); assertTrue(new GoogleStorageFindFeature(session).find(container)); final String prefix = new AlphanumericRandomStringService()....
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokeRoundingEven() { FunctionTestUtil.assertResult(roundHalfUpFunction.invoke(BigDecimal.valueOf(10.25)), BigDecimal.valueOf(10)); FunctionTestUtil.assertResult(roundHalfUpFunction.invoke(BigDecimal.valueOf(10.25), BigDecimal.ONE), BigDecimal.valueO...
private void updateServiceInstance(Object result) { final Optional<Object> getServer = ReflectUtils.invokeMethod(result, "getServer", null, null); if (!getServer.isPresent()) { return; } RetryContext.INSTANCE.updateServiceInstance(getServer.get()); }
@Test public void testBefore() throws Exception { final Interceptor interceptor = getInterceptor(); final ExecuteContext context = interceptor.before(TestHelper.buildDefaultContext()); assertNull(context.getResult()); final RetryRule retryRule = new RetryRule(); retryRule.set...
public static List<Chunk> split(String s) { int pos = s.indexOf(SLASH); if (pos == -1) { throw new RuntimeException("path did not start with or contain '/'"); } List<Chunk> list = new ArrayList(); int startPos = 0; int searchPos = 0; boolean anyDepth =...
@Test void testPathEdge() { List<PathSearch.Chunk> list = PathSearch.split("/hello//world"); logger.debug("list: {}", list); PathSearch.Chunk first = list.get(0); assertFalse(first.anyDepth); assertEquals("hello", first.controlType); PathSearch.Chunk second = list.get...
@Override public CompletableFuture<Void> readAsync(String path, OutputStream outputStream) { return openLogManagerAsync(path) .thenCompose(DLInputStream::openReaderAsync) .thenCompose(dlInputStream -> dlInputStream.readAsync(outputStream)) .thenCompose(DLInputStream::clos...
@Test(timeOut = 60000) public void testReadNonExistentData() { String testPath = "non-existent-path"; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { storage.readAsync(testPath, outputStream).get(); } catch (Exception e) { assertTrue(e...
public T getNewState() { return newState; }
@Test public void testGetNewState() { assertEquals(ClusterState.ACTIVE, clusterStateChange.getNewState()); assertEquals(ClusterState.ACTIVE, clusterStateChangeSameAttributes.getNewState()); assertEquals(Version.UNKNOWN, clusterStateChangeOtherType.getNewState()); assertEquals(Cluster...
@Override protected void validateDataImpl(TenantId tenantId, DeviceProfile deviceProfile) { validateString("Device profile name", deviceProfile.getName()); if (deviceProfile.getType() == null) { throw new DataValidationException("Device profile type should be specified!"); } ...
@Test void testValidateDeviceProfile_Lwm2mBootstrap_ShortServerId_Ok() { Integer shortServerId = 123; Integer shortServerIdBs = 0; DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs); validator.validateDataImpl(tenantId, deviceProfile); verify(vali...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Credentials Credentials = (Credentials) o; return Objects.equals(username, Credentials.username) && Objects.equals(password, Credentials....
@Test public void testList() { String username = "Prometheus"; String password = "secret"; Credentials credentials1 = new Credentials(username, password); Credentials credentials2 = new Credentials(username, password + "X"); assertFalse(credentials1.equals(credentials2)); ...
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { ...
@Test public void testCollectFetchInitializationWithUpdateHighWatermarkOnNotAssignedPartition() { final TopicPartition topicPartition0 = new TopicPartition("topic", 0); final long fetchOffset = 42; final long highWatermark = 1000; final SubscriptionState subscriptions = mock(Subscrip...
public static Table resolveCalciteTable(SchemaPlus schemaPlus, List<String> tablePath) { Schema subSchema = schemaPlus; // subSchema.getSubschema() for all except last for (int i = 0; i < tablePath.size() - 1; i++) { subSchema = subSchema.getSubSchema(tablePath.get(i)); if (subSchema == null) {...
@Test public void testMissingSubschema() { String subSchema = "fake_schema"; String tableName = "fake_table"; when(mockSchemaPlus.getSubSchema(subSchema)).thenReturn(null); Assert.assertThrows( IllegalStateException.class, () -> { TableResolution.resolveCalciteTable( ...
public Integer doCall() throws Exception { if (all) { client(Integration.class).delete(); printer().println("Integrations deleted"); } else { if (names == null) { throw new RuntimeCamelException("Missing integration name as argument or --all option.");...
@Test public void shouldHandleIntegrationNotFound() throws Exception { IntegrationDelete command = createCommand(); command.names = new String[] { "mickey-mouse" }; command.doCall(); Assertions.assertEquals("Integration mickey-mouse deletion skipped - not found", printer.getOutput()...