focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void finish() throws IOException { if (finished) { return; } flush(); // Finish the stream with the terminatorValue. VarInt.encode(terminatorValue, os); if (!BUFFER_POOL.offer(buffer)) { // The pool is full, we can't store the buffer. We just drop the buffer. } finishe...
@Test public void testFinishingWhenFinishedIsNoOp() throws Exception { BufferedElementCountingOutputStream os = testValues(toBytes("a")); os.finish(); os.finish(); os.finish(); }
@Override public String getActions() { return actions; }
@Test void testActions() { assertEquals("A B C", new InstantiatableInstancePermission(getClass().getSimpleName(), "A", "B", "C").getActions()); }
Converter<E> compile() { head = tail = null; for (Node n = top; n != null; n = n.next) { switch (n.type) { case Node.LITERAL: addToList(new LiteralConverter<E>((String) n.getValue())); break; case Node.COMPOSITE_KEYWORD: CompositeNode cn = (CompositeNode) n; ...
@Test public void testCompositeFormatting() throws Exception { { Parser<Object> p = new Parser<Object>("xyz %4.10(ABC)"); p.setContext(context); Node t = p.parse(); Converter<Object> head = p.compile(t, converterMap); String result = write(head, new Object()); assertEquals("xyz...
public <T> CompletableFuture<T> scheduleWriteOperation( String name, TopicPartition tp, Duration timeout, CoordinatorWriteOperation<S, T, U> op ) { throwIfNotRunning(); log.debug("Scheduled execution of write operation {}.", name); CoordinatorWriteEvent<T> eve...
@Test public void testScheduleWriteOpWhenInactive() { MockTimer timer = new MockTimer(); CoordinatorRuntime<MockCoordinatorShard, String> runtime = new CoordinatorRuntime.Builder<MockCoordinatorShard, String>() .withTime(timer.time()) .withTimer(timer) ...
@Override public byte[] encode(ILoggingEvent event) { var baos = new ByteArrayOutputStream(); try (var generator = jsonFactory.createGenerator(baos)) { generator.writeStartObject(); // https://cloud.google.com/logging/docs/structured-logging#structured_logging_special_fields // https://gith...
@Test void encode_error() { var e = mockEvent(); when(e.getLevel()).thenReturn(Level.ERROR); when(e.getFormattedMessage()).thenReturn("what a terrible failure"); var msg = encoder.encode(e); assertMatchesJson( """ {"@type":"type.googleapis.com/google.devtools.clouderro...
public HttpResponse get(Application application, String hostName, String serviceType, Path path, Query query) { return get(application, hostName, serviceType, path, query, null); }
@Test public void testNormalGetWithRewrite() throws Exception { ArgumentCaptor<HttpFetcher.Params> actualParams = ArgumentCaptor.forClass(HttpFetcher.Params.class); ArgumentCaptor<URI> actualUrl = ArgumentCaptor.forClass(URI.class); doAnswer(invoc -> new StaticResponse(200, "application/json...
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void equality() { ULiteral oneLit = ULiteral.intLit(1); ULiteral twoLit = ULiteral.intLit(2); ULiteral piLit = ULiteral.doubleLit(Math.PI); ULiteral trueLit = ULiteral.booleanLit(true); ULiteral falseLit = ULiteral.booleanLit(false); new EqualsTester() .addEqualityGroup(U...
public static BigInteger signedMessageToKey(byte[] message, SignatureData signatureData) throws SignatureException { return signedMessageHashToKey(Hash.sha3(message), signatureData); }
@Test public void testSignedMessageToKey() throws SignatureException { Sign.SignatureData signatureData = Sign.signPrefixedMessage(TEST_MESSAGE, SampleKeys.KEY_PAIR); BigInteger key = Sign.signedPrefixedMessageToKey(TEST_MESSAGE, signatureData); assertEquals(key, (SampleKeys....
@Override public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignClientFactory context, Target.HardCodedTarget<T> target) { if (!(feign instanceof PolarisFeignCircuitBreaker.Builder)) { return feign.target(target); } PolarisFeignCircuitBreaker.Builder builder = (PolarisFeignCircuitBr...
@Test public void testTarget3() { PolarisFeignCircuitBreakerTargeter targeter = new PolarisFeignCircuitBreakerTargeter(circuitBreakerFactory, circuitBreakerNameResolver); FeignClientFactoryBean feignClientFactoryBean = mock(FeignClientFactoryBean.class); doReturn(void.class).when(feignClientFactoryBean).getFallb...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 0 && "currentTimeMillis".equals(methodName)) { return SelLong.of(DateTimeUtils.currentTimeMillis()); } // no-op to support Arrays.asList if (args.length == 1 && "asList".equals(methodName)) { return args[...
@Test(expected = UnsupportedOperationException.class) public void testCallCurrentTimeMillisWithWrongArgs() { SelMiscFunc.INSTANCE.call("currentTimeMillis", new SelType[1]); }
@ManagedOperation(description = "set job executor activate") public void setJobExecutorActivate(Boolean active) { if (active) jobExecutor.start(); else jobExecutor.shutdown(); }
@Test public void setJobExecutorActivateTrue() { jobExecutorMbean.setJobExecutorActivate(true); verify(jobExecutor).start(); jobExecutorMbean.setJobExecutorActivate(false); verify(jobExecutor).shutdown(); }
@Override public final void dispose() { if (unsubscribed.compareAndSet(false, true)) { if (AutoDisposeAndroidUtil.isMainThread()) { onDispose(); } else { AndroidSchedulers.mainThread().scheduleDirect(this::onDispose); } } }
@Test public void onDisposeFailsWhenMainThreadCheckNotSet() { try { new MainThreadDisposable() { @Override protected void onDispose() {} }.dispose(); throw new AssertionError("Expected to fail before this due to Looper not being stubbed!"); } catch (RuntimeException e) { ...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Constraints annotations in models") public void testTicket3731() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Ticket3731Resource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /test/cart:\n" + ...
public static RowCoder of(Schema schema) { return new RowCoder(schema); }
@Test public void testNestedTypes() throws Exception { Schema nestedSchema = Schema.builder().addInt32Field("f1_int").addStringField("f1_str").build(); Schema schema = Schema.builder().addInt32Field("f_int").addRowField("nested", nestedSchema).build(); Row nestedRow = Row.withSchema(nestedSchema)...
@Override public SingleRuleConfiguration build() { return new SingleRuleConfiguration(); }
@SuppressWarnings("rawtypes") @Test void assertBuild() { DefaultDatabaseRuleConfigurationBuilder builder = OrderedSPILoader.getServices(DefaultDatabaseRuleConfigurationBuilder.class, Collections.singleton(new SingleRuleBuilder())).values().iterator().next(); assertThat(builder.bu...
@Override public String key() { return PropertyType.BOOLEAN.name(); }
@Test public void key() { assertThat(underTest.key()).isEqualTo("BOOLEAN"); }
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"}) public static boolean isScalablePushQuery( final Statement statement, final KsqlExecutionContext ksqlEngine, final KsqlConfig ksqlConfig, final Map<String, Object> overrides ) { if (!isPushV2Enabled(ksqlConfig, ov...
@Test public void shouldNotMakeQueryWithRowoffsetInWhereClauseScalablePush() { try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) { // Given: expectIsSPQ(ColumnName.of("foo"), columnExtractor); givenWhereClause(SystemColumns.ROWOFFSET_NAME, columnExtractor); ...
public OpenConfigAssignmentHandler addConfig(OpenConfigConfigOfAssignmentHandler config) { modelObject.config(config.getModelObject()); return this; }
@Test public void testAddConfig() { // test Handler OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentHandler(2, parent); // call addConfig OpenConfigConfigOfAssignmentHandler configOfAssignment = new OpenConfigConfigOfAssignmentHandler(assignment); ...
@Udf(description = "Returns a new string with all matches of regexp in str replaced with newStr") public String regexpReplace( @UdfParameter( description = "The source string. If null, then function returns null.") final String str, @UdfParameter( description = "The regexp to match." ...
@Test public void shouldReplace() { assertThat(udf.regexpReplace("foobar", "foo", "bar"), is("barbar")); assertThat(udf.regexpReplace("foobar", "fooo", "bar"), is("foobar")); assertThat(udf.regexpReplace("foobar", "o", ""), is("fbar")); assertThat(udf.regexpReplace("abc", "", "n"), is("nanbncn")); ...
@Override public HttpResponseOutputStream<File> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String location = new StoregateWriteFeature(session, fileid).start(file, status); final MultipartOutputStream proxy = new Multipar...
@Test public void testReadWrite() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path folder = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), ...
@Override public String getOriginalHost() { try { if (originalHost == null) { originalHost = getOriginalHost(getHeaders(), getServerName()); } return originalHost; } catch (URISyntaxException e) { throw new IllegalArgumentException(e); ...
@Test void testGetOriginalHost_handlesNonRFC2396Hostnames() { config.setProperty("zuul.HttpRequestMessage.host.header.strict.validation", false); HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "my_underscore_endpoint.netflix...
@Override public long put(final K key, final V value, final long timestamp) { return internal.put(key, value, timestamp); }
@Test public void shouldDelegateAndRecordMetricsOnPut() { when(inner.put(RAW_KEY, RAW_VALUE, TIMESTAMP)).thenReturn(PUT_RETURN_CODE_VALID_TO_UNDEFINED); final long validto = store.put(KEY, VALUE, TIMESTAMP); assertThat(validto, is(PUT_RETURN_CODE_VALID_TO_UNDEFINED)); assertThat((D...
@Override public void handle(CommitterEvent event) { try { eventQueue.put(event); } catch (InterruptedException e) { throw new YarnRuntimeException(e); } }
@Test public void testCommitWindow() throws Exception { Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir); AsyncDispatcher dispatcher = new AsyncDispatcher(); dispatcher.init(conf); dispatcher.start(); TestingJobEventHandler jeh = new TestingJobEven...
@Override public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext) { doEvaluateDisruptContext(request, requestContext); return _client.sendRequest(request, requestContext); }
@Test public void testDisruptSourceAlreadySet() { when(_context.getLocalAttr(eq(DISRUPT_SOURCE_KEY))).thenReturn(any(String.class)); _client.sendRequest(_request, _context); verify(_context, never()).putLocalAttr(eq(DISRUPT_CONTEXT_KEY), any(String.class)); }
@Override public String getQueryLimitPart(int limit) { return Queries.postgresSqlLimitPart(limit); }
@Test void test() { assertTrue(jdbcCustomization.supportsExplicitQueryLimitPart()); Arrays.asList(1, 5, 20, 100) .forEach(it -> assertEquals(" LIMIT " + it, jdbcCustomization.getQueryLimitPart(it))); }
public int getKafkaBufferSize() { return _kafkaBufferSize; }
@Test public void testGetKafkaBufferSize() { // test default KafkaPartitionLevelStreamConfig config = getStreamConfig("topic", "host1", null, ""); Assert.assertEquals(KafkaStreamConfigProperties.LowLevelConsumer.KAFKA_BUFFER_SIZE_DEFAULT, config.getKafkaBufferSize()); config = getStreamConfig...
public static Build withPropertyValue(String propertyValue) { return new Builder(propertyValue); }
@Test void it_should_return_transport_as_default_value_when_property_is_null() { //GIVEN String nullValue = null; //WHEN ElasticsearchClientType clientType = ElasticsearchClientTypeBuilder.withPropertyValue(nullValue).build(); //THEN assertEquals(TRANSPORT, clientType); }
public static long getNumSector(String requestSize, String sectorSize) { Double memSize = Double.parseDouble(requestSize); Double sectorBytes = Double.parseDouble(sectorSize); Double nSectors = memSize / sectorBytes; Double memSizeKB = memSize / 1024; Double memSizeGB = memSize / (1024 * 1024 * 1024...
@Test public void getSectorTestTB() { String testRequestSize = "1099511627776"; // 1TB String testSectorSize = "512"; long result = HFSUtils.getNumSector(testRequestSize, testSectorSize); assertEquals(2179753739L, result); }
public static short translateBucketAcl(GSAccessControlList acl, String userId) { short mode = (short) 0; for (GrantAndPermission gp : acl.getGrantAndPermissions()) { Permission perm = gp.getPermission(); GranteeInterface grantee = gp.getGrantee(); if (perm.equals(Permission.PERMISSION_READ)) {...
@Test public void translateAuthenticatedUserWritePermission() { GroupGrantee authenticatedUsersGrantee = GroupGrantee.AUTHENTICATED_USERS; mAcl.grantPermission(authenticatedUsersGrantee, Permission.PERMISSION_WRITE); assertEquals((short) 0200, GCSUtils.translateBucketAcl(mAcl, ID)); assertEquals((shor...
public static int listIndex(int i, int size) { return i < 0 ? size + i : i; }
@Test public void testListIndexOutOfBounds() { assertEquals(0, Accessors.listIndex(0, 10)); assertEquals(1, Accessors.listIndex(1, 10)); assertEquals(9, Accessors.listIndex(9, 10)); assertEquals(9, Accessors.listIndex(-1, 10)); assertEquals(1, Accessors.listIndex(-9, 10)); ...
public Operation parseMethod( Method method, List<Parameter> globalParameters, JsonView jsonViewAnnotation) { JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass()); return parseMethod( classType.getClass(), ...
@Test(description = "Responses") public void testGetResponses() { Reader reader = new Reader(new OpenAPI()); Method[] methods = ResponsesResource.class.getMethods(); Operation responseOperation = reader.parseMethod(Arrays.stream(methods).filter( (method -> method.getName()....
@CheckReturnValue @NonNull public static Observable<Boolean> observeNightModeState( @NonNull Context context, @StringRes int enablePrefResId, @BoolRes int defaultValueResId) { final Observable<Boolean> nightMode = ((AnyApplication) context.getApplicationContext()).getNightModeObservable(); final...
@Test public void testNeverNightMode() { SharedPrefsHelper.setPrefsValue(R.string.settings_key_night_mode, "never"); AtomicBoolean atomicBoolean = new AtomicBoolean(); AnyApplication application = getApplicationContext(); final Disposable subscribe = NightMode.observeNightModeState(applicatio...
@Override public Optional<Decision> onBufferFinished(int numTotalUnSpillBuffers, int currentPoolSize) { return numTotalUnSpillBuffers < numBuffersTriggerSpillingRatio * currentPoolSize ? Optional.of(Decision.NO_ACTION) : Optional.empty(); }
@Test void testOnBufferFinishedUnSpillBufferEqualToOrGreatThenThreshold() { final int poolSize = 10; Optional<Decision> finishedDecision = spillStrategy.onBufferFinished( (int) (poolSize * NUM_BUFFERS_TRIGGER_SPILLING_RATIO), poolSize); assertThat(fini...
@Override public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) { log.trace("compiling {} {}", intent, installable); ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint(); ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint(); ...
@Test public void testBandwidthConstrainedIntentFailure() { final double bpsTotal = 10.0; final ResourceService resourceService = MockResourceService.makeCustomBandwidthResourceService(bpsTotal); final List<Constraint> constraints = Collections.singletonList(...
@Override public void deleteArticleCategory(Long id) { // 校验存在 validateArticleCategoryExists(id); // 校验是不是存在关联文章 Long count = articleService.getArticleCountByCategoryId(id); if (count > 0) { throw exception(ARTICLE_CATEGORY_DELETE_FAIL_HAVE_ARTICLES); } ...
@Test public void testDeleteArticleCategory_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> articleCategoryService.deleteArticleCategory(id), ARTICLE_CATEGORY_NOT_EXISTS); }
@Override public Map<TupleTag<?>, PValue> getAdditionalInputs() { return delegate().getAdditionalInputs(); }
@Test public void getAdditionalInputsDelegates() { Map<TupleTag<?>, PValue> additionalInputs = ImmutableMap.of(new TupleTag<>("test_tag"), Pipeline.create().apply(Create.of("1"))); when(delegate.getAdditionalInputs()).thenReturn(additionalInputs); assertThat(forwarding.getAdditionalInputs(), equal...
public void enqueue(ByteBuffer payload) throws QueueException { final int messageSize = LENGTH_HEADER_SIZE + payload.remaining(); if (headSegment.hasSpace(currentHeadPtr, messageSize)) { LOG.debug("Head segment has sufficient space for message length {}", LENGTH_HEADER_SIZE + payload.remaini...
@Test public void insertSomeDataIntoNewQueue() throws QueueException, IOException { final QueuePool queuePool = QueuePool.loadQueues(tempQueueFolder, PAGE_SIZE, SEGMENT_SIZE); final Queue queue = queuePool.getOrCreate("test"); queue.enqueue(ByteBuffer.wrap("AAAA".getBytes(StandardCharsets.UT...
@Override public byte[] serialize(final String topic, final TimestampedKeyAndJoinSide<K> data) { final byte boolByte = (byte) (data.isLeftSide() ? 1 : 0); final byte[] keyBytes = keySerializer.serialize(topic, data.getKey()); final byte[] timestampBytes = timestampSerializer.serialize(topic,...
@Test public void shouldThrowIfSerializeNullData() { assertThrows(NullPointerException.class, () -> STRING_SERDE.serializer().serialize(TOPIC, TimestampedKeyAndJoinSide.makeLeft(null, 0))); }
public URL getInterNodeListener( final Function<URL, Integer> portResolver ) { return getInterNodeListener(portResolver, LOGGER); }
@Test public void shouldThrowIfExplicitInterNodeListenerHasIpv6WildcardAddress() { // Given: final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder() .putAll(MIN_VALID_CONFIGS) .put(ADVERTISED_LISTENER_CONFIG, "https://[::]:1236") .build() ); // ...
public MessageType convert(Schema avroSchema) { if (!avroSchema.getType().equals(Schema.Type.RECORD)) { throw new IllegalArgumentException("Avro schema must be a record."); } return new MessageType(avroSchema.getFullName(), convertFields(avroSchema.getFields(), "")); }
@Test public void testTimestampMicrosType() throws Exception { Schema date = LogicalTypes.timestampMicros().addToSchema(Schema.create(LONG)); Schema expected = Schema.createRecord( "myrecord", null, null, false, Arrays.asList(new Schema.Field("timestamp", date, null, null))); testRoundTripConvers...
@ScalarOperator(LESS_THAN) @SqlType(StandardTypes.BOOLEAN) public static boolean lessThan(@SqlType(StandardTypes.SMALLINT) long left, @SqlType(StandardTypes.SMALLINT) long right) { return left < right; }
@Test public void testLessThan() { assertFunction("SMALLINT'37' < SMALLINT'37'", BOOLEAN, false); assertFunction("SMALLINT'37' < SMALLINT'17'", BOOLEAN, false); assertFunction("SMALLINT'17' < SMALLINT'37'", BOOLEAN, true); assertFunction("SMALLINT'17' < SMALLINT'17'", BOOLEAN, fa...
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) { SinkConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!existingC...
@Test public void testMergeDifferentCleanupSubscription() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("cleanupSubscription", false); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertFalse(m...
@Override public void define(Context context) { NewController controller = context.createController(CONTROLLER_COMPONENTS) .setSince("4.2") .setDescription("Get information about a component (file, directory, project, ...) and its ancestors or descendants. " + "Update a project or module key."...
@Test public void define_controller() { WebService.Context context = new WebService.Context(); new ComponentsWs(action).define(context); WebService.Controller controller = context.controller(CONTROLLER_COMPONENTS); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpt...
public static ConnectorConfigGenerator create(final SourceConnector connector, final Class<?> dbzConfigClass) { return create(connector, dbzConfigClass, Collections.emptySet(), Collections.emptyMap()); }
@Test void testIfItHandlesWrongClassInput() { final MySqlConnector connector = new MySqlConnector(); final Map<String, Object> overridenDefaultValues = Collections.emptyMap(); final Set<String> requiredFields = Collections.emptySet(); Class<?> clazz = getClass(); assertThro...
@Deprecated static void updateBlockHandlerFor(Class<?> clazz, String name, Method method) { if (clazz == null || StringUtil.isBlank(name)) { throw new IllegalArgumentException("Bad argument"); } BLOCK_HANDLER_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method)); }
@Test(expected = IllegalArgumentException.class) public void testUpdateFallbackBadArgument() { ResourceMetadataRegistry.updateBlockHandlerFor(String.class, "", new Class[0], String.class.getMethods()[0]); }
@Override public int getNettyWriteBufferLowWaterMark() { return clientConfig.getPropertyAsInteger(WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_BUFFER_LOW_WATER_MARK); }
@Test void testGetNettyWriteBufferLowWaterMarkOverride() { clientConfig.set(ConnectionPoolConfigImpl.WRITE_BUFFER_LOW_WATER_MARK, 10000); assertEquals(10000, connectionPoolConfig.getNettyWriteBufferLowWaterMark()); }
@Override public T getHollowObject(int ordinal) { List<T> refCachedItems = cachedItems; if (refCachedItems == null) { throw new IllegalStateException(String.format("HollowObjectCacheProvider for type %s has been detached or was not initialized", typeReadState == null ? null : typeReadSta...
@Test public void adding_withPreExisting() { TypeA a2 = typeA(2); prepopulate(typeA(0), typeA(1)); notifyAdded(a2); assertEquals(a2, subject.get().getHollowObject(a2.ordinal)); }
public ResourceMethodDescriptor process(final ServerResourceContext context) { String path = context.getRequestURI().getRawPath(); if (path.length() < 2) { throw new RoutingException(HttpStatus.S_404_NOT_FOUND.getCode()); } if (path.charAt(0) == '/') { path = path.substring(1); ...
@Test public void failsOnRootResourceMethodNotFound() throws URISyntaxException { final TestSetup setup = new TestSetup(); setup.mockContextForMethodNotFound(setup._rootPath); final RestLiRouter router = setup._router; final ServerResourceContext context = setup._context; final RoutingException...
public TimerProducer(MetricsEndpoint endpoint) { super(endpoint); }
@Test public void testTimerProducer() { assertThat(producer, is(notNullValue())); assertThat(producer.getEndpoint().equals(endpoint), is(true)); }
public static void deletePathQuietly(String toDelete) { try { Path toRemovePath = new Path(toDelete); FileSystem fs = toRemovePath.getFileSystem(); if (fs.exists(toRemovePath)) { fs.delete(toRemovePath, true); } } catch (IOException e) { ...
@Test void testDeletePathQuietly() throws IOException { File testFile = new File(tempFolder.getPath(), "testFile"); Files.createFile(testFile.toPath()); assertThat(testFile).exists(); SegmentPartitionFile.deletePathQuietly(testFile.getPath()); assertThat(testFile).doesNotExis...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void answerCallback() { // callbackQuery sent by client after pressing on InlineKeyboardButton (used in sendGame() test) CallbackQuery callbackQuery = BotUtils.parseUpdate(testCallbackQuery).callbackQuery(); assertNotNull(callbackQuery); assertFalse(callbackQuery.id().i...
public String getBindingActualTable(final String dataSource, final String logicTable, final String otherLogicTable, final String otherActualTable) { Optional<ShardingTable> otherShardingTable = Optional.ofNullable(shardingTables.get(otherLogicTable)); int index = otherShardingTable.map(optional -> optio...
@Test void assertGetBindingActualTablesFailureWhenNotFound() { assertThrows(ActualTableNotFoundException.class, () -> createBindingTableRule().getBindingActualTable("no_ds", "Sub_Logic_Table", "LOGIC_TABLE", "table_1")); }
@Override public void setHeaders(URLConnection connection, HTTPSamplerBase sampler) throws IOException { // Get the encoding to use for the request String contentEncoding = sampler.getContentEncoding(); long contentLength = 0L; boolean hasPutBody = false; // Check if the hea...
@Test public void testSetHeadersWithParams() throws Exception { URLConnection uc = new NullURLConnection(); HTTPSampler sampler = new HTTPSampler(); sampler.setHTTPFiles(new HTTPFileArg[] { new HTTPFileArg("file2", "param2", "mime2") }); Arguments arguments = new Argu...
@Override public List<ParsedStatement> parse(final String sql) { return primaryContext.parse(sql); }
@Test public void shouldBeAbleToParseInvalidThings() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); // No Stream called 'I_DO_NOT_EXIST' exists // When: final List<ParsedStatement> parsed = ksqlEngine .parse("CREATE STREAM FOO AS SELECT * FROM I_DO_NOT_EXIST;"); // Then: ...
@Override public DirectPipelineResult run(Pipeline pipeline) { try { options = MAPPER .readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class) .as(DirectOptions.class); } catch (IOException e) { throw new IllegalArgumentException( "Pipeli...
@Test public void transformDisplayDataExceptionShouldFail() { DoFn<Integer, Integer> brokenDoFn = new DoFn<Integer, Integer>() { @ProcessElement public void processElement(ProcessContext c) throws Exception {} @Override public void populateDisplayData(DisplayData.B...
private CompletionStage<RestResponse> report(RestRequest request) { ServerManagement server = invocationHelper.getServer(); return Security.doAs(request.getSubject(), () -> server.getServerReport().handle((path, t) -> { if (t != null) { throw CompletableFutures.asCompletionE...
@Test public void testServerReport() { CompletionStage<RestResponse> response = adminClient.server().report(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("application/gzip"); }
@Override public <T> void register(Class<T> remoteInterface, T object) { register(remoteInterface, object, 1); }
@Test public void testNoAckWithResultInvocationsAsync() throws InterruptedException, ExecutionException { RedissonClient server = createInstance(); RedissonClient client = createInstance(); try { server.getRemoteService().register(RemoteInterface.class, new RemoteImpl()); ...
public static ConjunctFuture<Void> completeAll( Collection<? extends CompletableFuture<?>> futuresToComplete) { return new CompletionConjunctFuture(futuresToComplete); }
@Test void testCompleteAllPartialExceptional() { final CompletableFuture<String> inputFuture1 = new CompletableFuture<>(); final CompletableFuture<Integer> inputFuture2 = new CompletableFuture<>(); final List<CompletableFuture<?>> futuresToComplete = Arrays.asList(inputFutur...
@Override public String toString() { return toStringHelper(this) .add("flushPolicy", flushPolicy) .add("rowGroupMaxRowCount", rowGroupMaxRowCount) .add("dictionaryMaxMemory", dictionaryMaxMemory) .add("dictionaryMemoryAlmostFullRange", dict...
@Test public void testToString() { DataSize stripeMinSize = new DataSize(13, MEGABYTE); DataSize stripeMaxSize = new DataSize(27, MEGABYTE); int stripeMaxRowCount = 1_100_000; int rowGroupMaxRowCount = 15_000; DataSize dictionaryMaxMemory = new DataSize(13_000, KILOBYTE);...
public static void move(String srcPath, String dstPath) throws IOException { Files.move(Paths.get(srcPath), Paths.get(dstPath), StandardCopyOption.REPLACE_EXISTING); }
@Test public void moveNonExistentFile() throws IOException { // ghostFile is never created, so deleting should fail File ghostFile = new File(mTestFolder.getRoot(), "ghost.txt"); File toFile = mTestFolder.newFile("to.txt"); mException.expect(IOException.class); FileUtils.move(ghostFile.getAbsolute...
@Nullable @Override public BlobHttpContent getContent() { return null; }
@Test public void testGetContent() { Assert.assertNull(testBlobChecker.getContent()); }
public ParseResult parse(File file) throws IOException, SchemaParseException { return parse(file, null); }
@Test void testParseFile() throws IOException { Path tempFile = Files.createTempFile("TestSchemaParser", null); Files.write(tempFile, singletonList(SCHEMA_JSON)); Schema schema = new SchemaParser().parse(tempFile.toFile()).mainSchema(); assertEquals(SCHEMA_REAL, schema); }
@Override public boolean isEmpty() { return targetMap.isEmpty(); }
@Test void isEmpty() { Assertions.assertFalse(lowerCaseLinkHashMap.isEmpty()); Assertions.assertTrue(new LowerCaseLinkHashMap<>().isEmpty()); }
@Override public YamlShardingStrategyConfiguration swapToYamlConfiguration(final ShardingStrategyConfiguration data) { YamlShardingStrategyConfiguration result = new YamlShardingStrategyConfiguration(); if (data instanceof StandardShardingStrategyConfiguration) { result.setStandard(creat...
@Test void assertSwapToYamlConfigurationForHintShardingStrategy() { ShardingStrategyConfiguration data = new HintShardingStrategyConfiguration("core_hint_fixture"); YamlShardingStrategyConfigurationSwapper swapper = new YamlShardingStrategyConfigurationSwapper(); YamlShardingStrategyConfigur...
public static void setCurator(CuratorFramework curator) { CURATOR_TL.set(curator); }
@Test public void testACLs() throws Exception { DelegationTokenManager tm1; String connectString = zkServer.getConnectString(); Configuration conf = getSecretConf(connectString); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); String userPass = "myuser:mypass"; final ACL digest...
@Override public Num calculate(BarSeries series, Position position) { return calculateProfit(series, position); }
@Test public void calculateWithOpenedPosition() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); // with base percentage should return 1 AnalysisCriterion retWithBase = getCriterion(); Position position1 = new Position(); assertNumEquals(1d,...
@Override public RuleNodePath getRuleNodePath() { return INSTANCE; }
@Test void assertNew() { RuleNodePathProvider ruleNodePathProvider = new ShadowRuleNodePathProvider(); RuleNodePath actualRuleNodePath = ruleNodePathProvider.getRuleNodePath(); assertThat(actualRuleNodePath.getNamedItems().size(), is(3)); assertTrue(actualRuleNodePath.getNamedItems()...
public void flipBit(int position) { bitSet.flip(position); }
@Test public static void testFlipBit() { Bitmap bitmap = new Bitmap(4096); for (int i = 0; i < 4096; i++) { bitmap.flipBit(i); assertTrue(bitmap.getBit(i)); bitmap.flipBit(i); assertFalse(bitmap.getBit(i)); bitmap.flipBit(i); ...
@Override public int getTransactionIsolation() { return Connection.TRANSACTION_NONE; }
@Test void assertGetTransactionIsolation() { assertThat(connection.getTransactionIsolation(), is(Connection.TRANSACTION_NONE)); }
public static String trimToType( String string, int trimType ) { switch ( trimType ) { case ValueMetaInterface.TRIM_TYPE_BOTH: return trim( string ); case ValueMetaInterface.TRIM_TYPE_LEFT: return ltrim( string ); case ValueMetaInterface.TRIM_TYPE_RIGHT: return rtrim( strin...
@Test public void testTrimToType() { final String source = " trim me hard "; assertEquals( "trim me hard", Const.trimToType( source, ValueMetaInterface.TRIM_TYPE_BOTH ) ); assertEquals( "trim me hard ", Const.trimToType( source, ValueMetaInterface.TRIM_TYPE_LEFT ) ); assertEquals( " trim me hard", Con...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Responses with array schema") public void testTicket2340() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Ticket2340Resource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /test/test:\n" + ...
public void connect() throws ConnectException { connect(s -> {}, t -> {}, () -> {}); }
@Test public void testInterruptCurrentThreadIfConnectionIsInterrupted() throws Exception { when(webSocketClient.connectBlocking()).thenThrow(new InterruptedException()); service.connect(); assertTrue(Thread.currentThread().isInterrupted(), "Interrupted flag was not set properly"); }
@Override public Num calculate(BarSeries series, Position position) { return series.one(); }
@Test public void calculateWithOnePosition() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); Position position = new Position(); AnalysisCriterion positionsCriterion = getCriterion(); assertNumEquals(1, positionsCriterion.calculate(series, posit...
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: ret...
@Test public void testConvertTypeCaseChar() { CharTypeInfo charTypeInfo = TypeInfoFactory.getCharTypeInfo(10); Type result = EntityConvertUtils.convertType(charTypeInfo); Type expectedType = ScalarType.createCharType(10); assertEquals(expectedType, result); }
public static void trimRecordTemplate(RecordTemplate recordTemplate, MaskTree override, final boolean failOnMismatch) { trimRecordTemplate(recordTemplate.data(), recordTemplate.schema(), override, failOnMismatch); }
@Test public void testRecursiveBasic() throws CloneNotSupportedException { LinkedListNode node1 = new LinkedListNode(); node1.setIntField(1); LinkedListNode node2 = new LinkedListNode(); node2.setIntField(2); node1.setNext(node2); RecordTemplate expected = node1.copy(); // Introduce b...
@Udf(description = "Converts a string representation of a date in the given format" + " into the number of milliseconds since 1970-01-01 00:00:00 UTC/GMT." + " Single quotes in the timestamp format can be escaped with ''," + " for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time...
@Test public void shouldThrowIfFormatInvalid() { // When: final KsqlFunctionException e = assertThrows( KsqlFunctionException.class, () -> udf.stringToTimestamp("2021-12-01 12:10:11.123", "invalid") ); // Then: assertThat(e.getMessage(), containsString("Unknown pattern letter: i")...
public void refresh() { kidElementCache = null; kidDirectoryCache = null; rd.clear(); populateChildren(); try { if ( obj != null ) { getRepositoryObjects(); } } catch ( KettleException ignored ) { // Ignored } fireCollectionChanged(); }
@Test public void testRefresh() throws Exception { RepositoryDirectory rd = Mockito.mock( RepositoryDirectory.class ); Mockito.when( rd.getObjectId() ).thenReturn( new LongObjectId( 0L ) ); UIRepositoryDirectory uiDir = new UIRepositoryDirectory( rd, null, null ); uiDir.populateChildren(); uiDir.g...
public String format() { StringBuilder builder = new StringBuilder(); for (RefeedActions.Entry entry : actions.getEntries()) { builder.append(entry.name() + ": Consider removing data and re-feed document type '" + entry.getDocumentType() + "' in cluster '" + entry....
@Test public void formatting_of_single_action() { RefeedActions actions = new ConfigChangeActionsBuilder(). refeed(CHANGE_ID, CHANGE_MSG, DOC_TYPE, CLUSTER, SERVICE_NAME). build().getRefeedActions(); assertEquals("field-type-change: Consider removing data and re-feed ...
public boolean hasCapacity(Node host, NodeResources requestedCapacity) { return availableCapacityOf(host).satisfies(requestedCapacity); }
@Test public void hasCapacity() { assertTrue(capacity.hasCapacity(host1, resources0)); assertTrue(capacity.hasCapacity(host1, resources1)); assertTrue(capacity.hasCapacity(host2, resources0)); assertTrue(capacity.hasCapacity(host2, resources1)); assertTrue(capacity.hasCapacit...
public boolean checkStateUpdater(final long now, final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) { addTasksToStateUpdater(); if (stateUpdater.hasExceptionsAndFailedTasks()) { handleExceptionsFromStateUpdater(); } if ...
@Test public void shouldReturnFalseFromCheckStateUpdaterIfActiveTasksAreRestoring() { when(stateUpdater.restoresActiveTasks()).thenReturn(true); final TasksRegistry tasks = mock(TasksRegistry.class); final TaskManager taskManager = setUpTaskManager(ProcessingMode.AT_LEAST_ONCE, tasks, true);...
@Override public void handlerRule(final RuleData ruleData) { Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> { SpringCloudRuleHandle springCloudRuleHandle = GsonUtils.getInstance().fromJson(s, SpringCloudRuleHandle.class); RULE_CACHED.get().cachedHandle(CacheKeyUtils.INST.ge...
@Test public void testHandlerRule() { ruleData.setSelectorId("1"); ruleData.setHandle("{\"urlPath\":\"test\"}"); ruleData.setId("test"); springCloudPluginDataHandler.handlerRule(ruleData); Supplier<CommonHandleCache<String, SpringCloudRuleHandle>> cache = SpringCloudPluginDat...
public static Map<String, Object> getTopologySummary(TopologyPageInfo topologyPageInfo, String window, Map<String, Object> config, String remoteUser) { Map<String, Object> result = new HashMap(); Map<String, Object> topologyConf = (Map<String, Obj...
@Test void test_getTopologyBoltAggStatsMap_hasNoLastError() { // Define inputs final String expectedBoltId = "MyBoltId"; // Build stats instance for our bolt final ComponentAggregateStats aggregateStats = buildBoltAggregateStatsBase(); addBoltStats(expectedBoltId, aggregateS...
@VisibleForTesting static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) { ImmutableSortedMap.Builder<OffsetRange, Integer> rval = ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE); List<OffsetRange> sortedRanges = Lists.newArrayList(ranges); if (...
@Test public void testOverlappingFroms() { Iterable<OffsetRange> ranges = Arrays.asList(range(0, 4), range(0, 8), range(0, 12)); Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition = computeOverlappingRanges(ranges); assertEquals( ImmutableMap.builder().put(range(0, 4),...
@Subscribe public void onPostMenuSort(PostMenuSort postMenuSort) { // The menu is not rebuilt when it is open, so don't swap or else it will // repeatedly swap entries if (client.isMenuOpen()) { return; } MenuEntry[] menuEntries = client.getMenuEntries(); // Build option map for quick lookup in fin...
@Test public void testSlayerMaster() { lenient().when(config.swapTrade()).thenReturn(true); when(config.swapAssignment()).thenReturn(true); entries = new MenuEntry[]{ menu("Cancel", "", MenuAction.CANCEL), menu("Rewards", "Duradel", MenuAction.NPC_FIFTH_OPTION), menu("Trade", "Duradel", MenuAction.NPC...
public static String processPattern(String pattern, TbMsg tbMsg) { try { String result = processPattern(pattern, tbMsg.getMetaData()); JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData()); if (json.isObject()) { Matcher matcher = DATA_PATTERN.matcher(result...
@Test public void testComplexObjectReplacement() { String pattern = "ABC ${key} $[key1.key2.key3]"; TbMsgMetaData md = new TbMsgMetaData(); md.putValue("key", "metadata_value"); ObjectNode key2Node = JacksonUtil.newObjectNode(); key2Node.put("key3", "value3"); Objec...
public static DataMap convertToDataMap(Map<String, Object> queryParams) { return convertToDataMap(queryParams, Collections.<String, Class<?>>emptyMap(), AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), RestLiProjectionDataMapSerializer.DEFAULT_SERIALIZER); }
@Test (expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Map key '1' is not of type String") public void testNonStringKeyToDataMap() { Map<String, Object> queryParams = new HashMap<>(); Map<Object, Object> hashMapParam = new HashMap<>(); hashMapParam.put(1, "...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PiExactFieldMatch that = (PiExactFieldMatch) o; return Objects.equal(this.fieldId(), that.fieldId()) && ...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(piExactFieldMatch1, sameAsPiExactFieldMatch1) .addEqualityGroup(piExactFieldMatch2) .testEquals(); }
@InterfaceAudience.Private @InterfaceStability.Unstable @VisibleForTesting public static void setLoginUser(UserGroupInformation ugi) { // if this is to become stable, should probably logout the currently // logged in ugi if it's different loginUserRef.set(ugi); }
@Test(timeout=10000) public void testSetLoginUser() throws IOException { UserGroupInformation ugi = UserGroupInformation.createRemoteUser("test-user"); UserGroupInformation.setLoginUser(ugi); assertEquals(ugi, UserGroupInformation.getLoginUser()); }
public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws SecurityException { return ReflectUtil.getMethod(clazz, methodName, parameterTypes); }
@Test public void getDeclaredMethod() { Method noMethod = ClassUtil.getDeclaredMethod(TestSubClass.class, "noMethod"); assertNull(noMethod); Method privateMethod = ClassUtil.getDeclaredMethod(TestSubClass.class, "privateMethod"); assertNotNull(privateMethod); Method publicMethod = ClassUtil.getDeclaredMetho...
public B dynamic(Boolean dynamic) { this.dynamic = dynamic; return getThis(); }
@Test void dynamic() { ServiceBuilder builder = new ServiceBuilder(); builder.dynamic(true); Assertions.assertTrue(builder.build().isDynamic()); builder.dynamic(false); Assertions.assertFalse(builder.build().isDynamic()); }
public static ApplicationBadgeLabeler get() { if(PreferencesFactory.get().getBoolean("queue.dock.badge")) { return new ApplicationBadgeLabelerFactory().create(); } return new DisabledApplicationBadgeLabeler(); }
@Test public void testGet() { assertNotNull(ApplicationBadgeLabelerFactory.get()); }
public RowExpression extract(PlanNode node) { return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null); }
@Test public void testProject() { PlanNode node = new ProjectNode(newId(), filter(baseTableScan, and( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))),...
public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; }
@Test public final void getNativeCacheShouldReturnTheRemoteCacheManagerSuppliedAtConstructionTime() { final RemoteCacheManager nativeCacheManagerReturned = objectUnderTest.getNativeCacheManager(); assertSame( "getNativeCacheManager() should have returned the RemoteCacheManager supplied at c...
protected boolean tryProcess1(@Nonnull Object item) throws Exception { return tryProcess(1, item); }
@Test public void when_tryProcess1_then_delegatesToTryProcess() throws Exception { // When boolean done = p.tryProcess1(MOCK_ITEM); // Then assertTrue(done); p.validateReceptionOfItem(ORDINAL_1, MOCK_ITEM); }
public FederationPolicyManager getPolicyManager(String queueName) throws YarnException { FederationPolicyManager policyManager = policyManagerMap.get(queueName); // If we don't have the policy manager cached, pull configuration // from the FederationStateStore to create and cache it if (policyMan...
@Test public void testGetWeightedHomePolicyManager() throws YarnException { stateStore = new MemoryFederationStateStore(); stateStore.init(new Configuration()); // root.b uses WeightedHomePolicyManager. // Step1. Prepare routerPolicyWeights. Map<SubClusterIdInfo, Float> routerPolicyWeights = new ...
@VisibleForTesting @Nullable Integer getUploadBufferSizeBytes() { return uploadBufferSizeBytes; }
@Test public void testUploadBufferSizeUserSpecified() { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); pipelineOptions.setGcsUploadBufferSizeBytes(12345); GcsUtil util = pipelineOptions.getGcsUtil(); assertEquals((Integer) 12345, util.getUploadBufferSizeBytes()); }
@Override public boolean isTerminal(Throwable failure) { return false; }
@Test public void isTerminal() { MessageListener<String> listener = createMessageListenerMock(); ReliableMessageListenerAdapter<String> adapter = new ReliableMessageListenerAdapter<>(listener); assertFalse(adapter.isTerminal(new RuntimeException())); assertFalse(adapter.isTerminal(n...
@Override public Object removeVariableLocally(String name) { return variables.remove(name); }
@Test public void testRemoveVariableLocally() { ProcessContextImpl context = new ProcessContextImpl(); context.setVariable("key", "value"); context.removeVariableLocally("key"); Assertions.assertEquals(0, context.getVariables().size()); }
@Override public int size2SizeIdx(int size) { return sizeClass.size2SizeIdx(size); }
@Test public void testSize2SizeIdx() { SizeClasses sc = new SizeClasses(PAGE_SIZE, PAGE_SHIFTS, CHUNK_SIZE, 0); PoolArena<ByteBuffer> arena = new PoolArena.DirectArena(null, sc); for (int sz = 0; sz <= CHUNK_SIZE; sz++) { int sizeIdx = arena.sizeClass.size2SizeIdx(sz); ...
public String getQualifiedName() { String column = identifier.getValueWithQuoteCharacters(); if (null != nestedObjectAttributes && !nestedObjectAttributes.isEmpty()) { column = String.join(".", column, nestedObjectAttributes.stream().map(IdentifierValue::getValueWithQuoteCharacters).collect(...
@Test void assertGetQualifiedNameWithoutOwner() { assertThat(new ColumnSegment(0, 0, new IdentifierValue("col")).getQualifiedName(), is("col")); }