focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@GET @Path("/entity-uid/{uid}/") @Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8) public TimelineEntity getEntity( @Context HttpServletRequest req, @Context HttpServletResponse res, @PathParam("uid") String uId, @QueryParam("confstoretrieve") String confsToRetrieve, @Q...
@Test void testGetEntitiesNoMatch() throws Exception { Client client = createClient(); try { URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/" + "timeline/clusters/cluster1/apps/app1/entities/app?" + "metricfilters=metric7%20ge%200&isrelatedto=type1:tid1_1:tid1_2," + ...
void snapshot(final PendingServiceMessageTracker tracker, final ErrorHandler errorHandler) { final int length = MessageHeaderEncoder.ENCODED_LENGTH + PendingMessageTrackerEncoder.BLOCK_LENGTH; final long nextServiceSessionId = correctNextServiceSessionId(tracker, errorHandler); idleStrategy...
@Test void snapshotPendingServiceMessageTrackerWithServiceMessagesMissedByFollower() { final int serviceId = 6; final PendingServiceMessageTracker pendingServiceMessageTracker = new PendingServiceMessageTracker( serviceId, mock(Counter.class), mock(LogPublisher.class), mock(ClusterCl...
@Override public void unsubscribePreCommit(String portId, Type eventType, InstancePortAdminService service, String className) { store.computeIfPresent(portId, (k, v) -> { if (className == null || className.isEmpty()) { return null; ...
@Test public void testUnsubscribePreCommit() { sampleSubscribe(); InstancePortAdminService service = new TestInstancePortAdminService(); target.unsubscribePreCommit(PORT_ID_1, OPENSTACK_PORT_PRE_REMOVE, service, CLASS_NAME_1); target.unsubscribePreCommit(PORT_ID_2, OPENSTACK_PORT_...
public void clear() { _intraPartMoveTasksByBrokerId.clear(); _interPartMoveTasksByBrokerId.clear(); _remainingLeadershipMovements.clear(); _remainingInterBrokerReplicaMovements.clear(); _remainingIntraBrokerReplicaMovements.clear(); }
@Test public void testClear() { List<ExecutionProposal> proposals = new ArrayList<>(); proposals.add(_leaderMovement1); proposals.add(_partitionMovement0); ExecutionTaskPlanner planner = new ExecutionTaskPlanner(null, new KafkaCruiseControlConfig(KafkaCruiseControlUnitTestUtils.getKafkaCruiseC...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (!(obj instanceof Rectangle)) { return false; } Rectangle other = (Rectangle) obj; if (Double.doubleToLongBits(this.left) != Double.doubleToLongBits(other.left)) { ...
@Test public void equalsTest() { Rectangle rectangle1 = create(1, 2, 3, 4); Rectangle rectangle2 = create(1, 2, 3, 4); Rectangle rectangle3 = create(3, 2, 3, 4); Rectangle rectangle4 = create(1, 4, 3, 4); Rectangle rectangle5 = create(1, 2, 1, 4); Rectangle rectangle6...
public String getFilepath() { return filepath; }
@Test public void testConstructorMessageAndThrowable() { Throwable cause = new RuntimeException( causeExceptionMessage ); try { throw new KettleFileNotFoundException( errorMessage, cause ); } catch ( KettleFileNotFoundException e ) { assertTrue( e.getMessage().contains( errorMessage ) ); ...
static String createTestId(String prefix) { String convertedPrefix = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_HYPHEN).convert(prefix); String formattedTimestamp = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS") .withZone(ZoneId.of("UTC")) .format(Instant.now()...
@Test public void testCreateTopicNameWithUppercase() { assertThat(createTestId("testWithUpperCase")).matches("test-with-upper-case-\\d{17}"); }
public final String key() { return key; }
@Test void trimsKey() { assertThat(new Tag<Object>(" x-foo ") { @Override protected String parseValue(Object input, TraceContext context) { return null; } }.key()).isEqualTo("x-foo"); }
@Override public Output run(RunContext runContext) throws Exception { String renderedNamespace = runContext.render(this.namespace); FlowService flowService = ((DefaultRunContext) runContext).getApplicationContext().getBean(FlowService.class); flowService.checkAllowedNamespace(runContext.ten...
@Test void shouldOutputTrueGivenExistingKey() throws Exception { // Given String namespaceId = "io.kestra." + IdUtils.create(); RunContext runContext = this.runContextFactory.of(Map.of( "flow", Map.of("namespace", namespaceId), "inputs", Map.of( "key",...
public void compress(byte[] data, int[] keys) throws IOException { OutputStream stream = new OutputStream(); byte[] compressedData; int length; switch (compression) { case CompressionType.NONE: compressedData = data; length = compressedData.length; break; case CompressionType.BZ2: comp...
@Test public void testCompress() throws IOException { int[] keys = new int[] { 4, 8, 15, 16 }; Random random = new Random(42L); byte[] data = new byte[1024]; random.nextBytes(data); Container container = new Container(GZ, -1); container.compress(data, keys); byte[] compressedData = container.dat...
@VisibleForTesting List<Container> getContainersFromPreviousAttemptsUnsafe(final Object response) { if (getContainersFromPreviousAttemptsMethod.isPresent() && response != null) { try { @SuppressWarnings("unchecked") final List<Container> containers = ...
@Test void testCallsGetContainersFromPreviousAttemptsMethodIfPresent() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class); final List<Container> ...
@Override public String rpcType() { return RpcTypeEnum.HTTP.getName(); }
@Test public void testRpcType() { assertEquals(RpcTypeEnum.HTTP.getName(), shenyuClientRegisterDivideService.rpcType()); }
public static boolean isConsoleOutput(String filePath) { return getConsoleOutputFolderAndFileName().equalsIgnoreCase(filePath); }
@Test public void shouldNotIdentifyAnyOtherArtifactAsConsoleLog() { assertThat(isConsoleOutput("artifact"), is(false)); }
@Override protected BitList<Invoker<T>> doRoute( BitList<Invoker<T>> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder<RouterSnapshotNode<T>> nodeHolder, Holder<String> messageHolder) throws RpcException {...
@Test void testRoute1() { StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); assertEquals(invokers, meshRuleRo...
@Override public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) { final ModelId modelId = entityDescriptor.id(); try { final RuleDao ruleDao = ruleService.load(modelId.id()); return Optional.of(exportNativeEntity(rule...
@Test @MongoDBFixtures("PipelineRuleFacadeTest.json") public void collectEntity() { final EntityDescriptor descriptor = EntityDescriptor.create("5adf25034b900a0fdb4e5338", ModelTypes.PIPELINE_RULE_V1); final EntityDescriptorIds entityDescriptorIds = EntityDescriptorIds.of(descriptor); fi...
public Optional<JobTriggerDto> getOneForJob(String jobDefinitionId) { final List<JobTriggerDto> triggers = getAllForJob(jobDefinitionId); // We are currently expecting only one trigger per job definition. This will most probably change in the // future once we extend our scheduler usage. ...
@Test @MongoDBFixtures("job-triggers.json") public void getForJob() { assertThatCode(() -> dbJobTriggerService.getOneForJob(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("jobDefinitionId"); assertThatCode(() -> dbJobTriggerService.get...
public <T> MongoCollection<T> nonEntityCollection(String collectionName, Class<T> valueType) { return getCollection(collectionName, valueType); }
@Test void testMongoIgnore() { // @MongoIgnore should prevent a property from being written to Mongo. But if it's returned from Mongo, // e.g. because it was calculated by an aggregation, it should be populated in the returned object. final MongoCollection<IgnoreTest> collection = collection...
public abstract void filter(Metadata metadata) throws TikaException;
@Test public void testDefault() throws Exception { Metadata metadata = new Metadata(); metadata.set("title", "title"); metadata.set("author", "author"); MetadataFilter defaultFilter = new DefaultMetadataFilter(); defaultFilter.filter(metadata); assertEquals(2, metad...
@SuppressWarnings("DataFlowIssue") public static CommandExecutor newInstance(final MySQLCommandPacketType commandPacketType, final CommandPacket commandPacket, final ConnectionSession connectionSession) throws SQLException { if (commandPacket instanceof SQLReceivedPacket) { log.debug("Execute pa...
@Test void assertNewInstanceWithComStmtReset() throws SQLException { assertThat(MySQLCommandExecutorFactory.newInstance(MySQLCommandPacketType.COM_STMT_RESET, mock(MySQLComStmtResetPacket.class), connectionSession), instanceOf(MySQLComStmtResetExecutor.class)); }
public static int getSuitableThreadCount() { return getSuitableThreadCount(THREAD_MULTIPLER); }
@Test void testGetSuitableThreadCount() { assertEquals(4, ThreadUtils.getSuitableThreadCount()); assertEquals(8, ThreadUtils.getSuitableThreadCount(3)); }
Map<Uuid, String> topicNames() { return topicNames; }
@Test public void testEmptyTopicNamesCacheBuiltFromTopicIds() { Map<String, Uuid> topicIds = new HashMap<>(); MetadataSnapshot cache = new MetadataSnapshot("clusterId", Collections.singletonMap(6, new Node(6, "localhost", 2077)), Collections.emptyList(), ...
public abstract MySqlSplit toMySqlSplit();
@Test public void testRecordSnapshotSplitState() { final MySqlSnapshotSplit split = new MySqlSnapshotSplit( TableId.parse("test_db.test_table"), "test_db.test_table-1", new RowType( Collec...
public static JsonToRowWithErrFn withExceptionReporting(Schema rowSchema) { return JsonToRowWithErrFn.forSchema(rowSchema); }
@Test @Category(NeedsRunner.class) public void testParsesRowsDeadLetterWithMissingFieldsNoErrors() throws Exception { PCollection<String> jsonPersons = pipeline.apply("jsonPersons", Create.of(JSON_PERSON_WITH_IMPLICIT_NULLS)); ParseResult results = jsonPersons.apply( JsonToRow....
@Override public CreateTopicsResult createTopics(final Collection<NewTopic> newTopics, final CreateTopicsOptions options) { final Map<String, KafkaFutureImpl<TopicMetadataAndConfig>> topicFutures = new HashMap<>(newTopics.size()); final CreatableTopicCollec...
@Test public void testCreateTopicsRetryThrottlingExceptionWhenEnabledUntilRequestTimeOut() throws Exception { long defaultApiTimeout = 60000; MockTime time = new MockTime(); try (AdminClientUnitTestEnv env = mockClientEnv(time, AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, St...
public <T> Future<Iterable<T>> multimapFetchSingleEntryFuture( ByteString encodedKey, ByteString encodedTag, String stateFamily, Coder<T> elemCoder) { StateTag<ByteString> stateTag = StateTag.<ByteString>of(Kind.MULTIMAP_SINGLE_ENTRY, encodedTag, stateFamily) .toBuilder() .setM...
@Test public void testReadMultimapSingleEntry() throws Exception { Future<Iterable<Integer>> future = underTest.multimapFetchSingleEntryFuture( STATE_MULTIMAP_KEY_1, STATE_KEY_1, STATE_FAMILY, INT_CODER); Mockito.verifyNoMoreInteractions(mockWindmill); Windmill.KeyedGetDataRequest.Bui...
public static String prettyJSON(String json) { return prettyJSON(json, TAB_SEPARATOR); }
@Test public void testRenderArrayInObject() throws Exception { assertEquals("{\n" + TAB + "\"foo\": [\n" + TAB + "]\n}", prettyJSON("{\"foo\":[]}")); }
public static <T> T toBean(Object source, Class<T> clazz) { return toBean(source, clazz, null); }
@Test public void mapToBeanTest2() { final HashMap<String, Object> map = MapUtil.newHashMap(); map.put("name", "Joe"); map.put("age", 12); // 非空构造也可以实例化成功 final Person2 person = BeanUtil.toBean(map, Person2.class, CopyOptions.create()); assertEquals("Joe", person.name); assertEquals(12, person.age); }
public static float getMem() { return (float) (1 - (double) OperatingSystemBeanManager.getFreePhysicalMem() / (double) OperatingSystemBeanManager.getTotalPhysicalMem()); }
@Test public void testGetMem() { systemBeanManagerMocked.when(() -> OperatingSystemBeanManager.getFreePhysicalMem()).thenReturn(123L); systemBeanManagerMocked.when(() -> OperatingSystemBeanManager.getTotalPhysicalMem()).thenReturn(2048L); assertEquals(EnvUtil.getMem(), 1 - ((double) 123L / (...
public final short readShort() throws IOException { if (input instanceof RandomAccessFile) { return ((RandomAccessFile) input).readShort(); } else if (input instanceof DataInputStream) { return ((DataInputStream) input).readShort(); } else { throw new Unsuppor...
@Test public void testReadShort() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(1, inStream.readShort()); // first short is 1 assertEquals(1, inStream.readShort()); // second short is 1 HollowBlobInput i...
@Override public boolean test(Pair<Point, Point> pair) { return testVertical(pair) && testHorizontal(pair); }
@Test public void testVertSeparation_allowMissingData() { Point p1 = (new PointBuilder()).time(EPOCH).latLong(0.0, 0.0).altitude(Distance.ofFeet(1000.0)).build(); Point p2 = (new PointBuilder()).time(EPOCH).latLong(0.0, 0.0).altitude(Distance.ofFeet(1000.0)).build(); Point p3 = (new PointBu...
public AggregateAnalysisResult analyze( final ImmutableAnalysis analysis, final List<SelectExpression> finalProjection ) { if (!analysis.getGroupBy().isPresent()) { throw new IllegalArgumentException("Not an aggregate query"); } final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ...
@Test public void shouldNotThrowOnNonAggregateFunctionIfAllParamsAreInGroupBy() { // Given: final Expression someExpression = mock(Expression.class); givenSelectExpression(new FunctionCall( FunctionName.of("UCASE"), ImmutableList.of(GROUP_BY_1, someExpression) )); // When: ana...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void loaderExceptionModCrash2() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/crash-report/loader_exception_mod_crash2.txt")), CrashReportAnalyzer.Rule.LOADING_CRASHED_FORGE); assertEquals...
public static String byteToHexString(final byte[] bytes, final int start, final int end) { if (bytes == null) { throw new IllegalArgumentException("bytes == null"); } int length = end - start; char[] out = new char[length * 2]; for (int i = start, j = 0; i < end; i+...
@Test void testHexArrayToString() { byte[] byteArray = new byte[] {1, -97, 49, 74}; String hex = StringUtils.byteToHexString(byteArray); assertThat(hex).isEqualTo("019f314a"); }
@Override public void encode(Event event, OutputStream output) throws IOException { String outputString = (format == null ? event.toString() : StringInterpolation.evaluate(event, format)); output.write(outputString.getBytes(charset)); }
@Test public void testEncodeWithCharset() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] rightSingleQuoteInUtf8 = {(byte) 0xE2, (byte) 0x80, (byte) 0x99}; String rightSingleQuote = new String(rightSingleQuoteInUtf8, Charset.forName("UTF-8")); ...
public RingbufferConfig setInMemoryFormat(InMemoryFormat inMemoryFormat) { checkNotNull(inMemoryFormat, "inMemoryFormat can't be null"); checkFalse(inMemoryFormat == NATIVE, "InMemoryFormat " + NATIVE + " is not supported"); this.inMemoryFormat = inMemoryFormat; return this; }
@Test(expected = NullPointerException.class) public void setInMemoryFormat_whenNull() { RingbufferConfig config = new RingbufferConfig(NAME); config.setInMemoryFormat(null); }
@Override public String getMethod() { return PATH; }
@Test public void testSetMyCommandsWithMoreThan100Commands() { SetMyCommands setMyCommands = SetMyCommands .builder() .languageCode("en") .scope(BotCommandScopeDefault.builder().build()) .build(); List<BotCommand> commands = new ArrayLi...
@Override public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return outerJoin(otherStream, toValueJoin...
@SuppressWarnings("deprecation") @Test public void shouldNotAllowNullValueJoinerOnOuterJoinWithStreamJoined() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.outerJoin( testStream, (ValueJoiner<? ...
@Override public synchronized int read() throws IOException { checkNotClosed(); if (finished) { return -1; } file.readLock().lock(); try { int b = file.read(pos++); // it's ok for pos to go beyond size() if (b == -1) { finished = true; } else { file.setLas...
@Test public void testRead_partialArray_sliceLarger() throws IOException { JimfsInputStream in = newInputStream(1, 2, 3, 4, 5, 6, 7, 8); byte[] bytes = new byte[12]; assertThat(in.read(bytes, 0, 10)).isEqualTo(8); assertArrayEquals(bytes(1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0), bytes); assertEmpty(in)...
public static <T> T fillBean(String className, Map<List<String>, Object> params, ClassLoader classLoader) { return fillBean(errorEmptyMessage(), className, params, classLoader); }
@Test public void fillBeanTestWithInitialInstanceTest() { Dispute dispute = new Dispute(); Map<List<String>, Object> paramsToSet = Map.of(List.of("creator", "firstName"), FIRST_NAME, List.of("creator", "age"), AGE); Object result = ScenarioBeanUtil.fillBean(of(dispute), Dispute.class.getCa...
public static JsonAsserter with(String json) { return new JsonAsserterImpl(JsonPath.parse(json).json()); }
@Test public void list_content_can_be_asserted_with_nested_matcher() throws Exception { with(JSON).assertThat("$..book[*]", hasItems(hasEntry("author", "Nigel Rees"), hasEntry("author", "Evelyn Waugh"))); }
@Override public PageData<WidgetsBundle> findAllTenantWidgetsBundlesByTenantId(WidgetsBundleFilter widgetsBundleFilter, PageLink pageLink) { return findTenantWidgetsBundlesByTenantIds(Arrays.asList(widgetsBundleFilter.getTenantId().getId(), NULL_UUID), widgetsBundleFilter, pageLink); }
@Test public void testFindAllWidgetsBundlesByTenantIdFullSearchScadaFirst() { UUID tenantId1 = Uuids.timeBased(); UUID tenantId2 = Uuids.timeBased(); for (int i = 0; i < 10; i++) { createWidgetBundles(5, tenantId1, "WB1_" + i + "_"); createWidgetBundles(2, tenantId1, ...
static DatanodeStorageInfo[] chooseTargetForNewBlock( BlockManager bm, String src, DatanodeInfo[] excludedNodes, String[] favoredNodes, EnumSet<AddBlockFlag> flags, ValidateAddBlockResult r) throws IOException { Node clientNode = null; boolean ignoreClientLocality = (flags != null ...
@Test @SuppressWarnings("unchecked") public void testIgnoreClientLocality() throws IOException { ValidateAddBlockResult addBlockResult = new ValidateAddBlockResult(1024L, 3, (byte) 0x01, null, null, null); EnumSet<AddBlockFlag> addBlockFlags = EnumSet.of(AddBlockFlag.IGNORE_CLIENT_LOCALITY)...
Map<ProjectionProducer<PTransform<?, ?>>, Map<PCollection<?>, FieldAccessDescriptor>> getPushdownOpportunities() { return pushdownOpportunities.build(); }
@Test public void testFieldAccessAllFields_returnsNoPushdown() { Pipeline p = Pipeline.create(); PCollection<Row> output = p.apply(new SimpleSource()); Map<PCollection<?>, FieldAccessDescriptor> pCollectionFieldAccess = ImmutableMap.of(output, FieldAccessDescriptor.withAllFields()); Projectio...
public static TypeBuilder<Schema> builder() { return new TypeBuilder<>(new SchemaCompletion(), new NameContext()); }
@Test void testFloat() { Schema.Type type = Schema.Type.FLOAT; Schema simple = SchemaBuilder.builder().floatType(); Schema expected = primitive(type, simple); Schema built1 = SchemaBuilder.builder().floatBuilder().prop("p", "v").endFloat(); assertEquals(expected, built1); }
@SuppressWarnings("java:S2583") public static boolean verify(@NonNull JWKSet jwks, @NonNull JWSObject jws) { if (jwks == null) { throw new IllegalArgumentException("no JWKS provided to verify JWS"); } if (jwks.getKeys() == null || jwks.getKeys().isEmpty()) { return false; } var head...
@Test void verify() throws ParseException { var jws = toJws(ECKEY, "hello world?").serialize(); var in = JWSObject.parse(jws); assertTrue(JwsVerifier.verify(JWKS, in)); }
@Override public boolean shouldFilter(HttpResponseMessage response) { if (!ENABLED.get() || !response.hasBody() || response.getContext().isInBrownoutMode()) { return false; } if (response.getContext().get(CommonContextKeys.GZIPPER) != null) { return true; } ...
@Test void prepareResponseBody_alreadyZipped() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip,deflate"); byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); response.getHeaders().set("Conten...
public String getNewLine( String fformat ) { String nl = System.getProperty( "line.separator" ); if ( fformat != null ) { if ( fformat.equalsIgnoreCase( "DOS" ) ) { nl = "\r\n"; } else if ( fformat.equalsIgnoreCase( "UNIX" ) ) { nl = "\n"; } } return nl; }
@Test public void testGetNewline() throws Exception { XMLOutputMeta xmlOutputMeta = new XMLOutputMeta(); assertEquals( "\r\n", xmlOutputMeta.getNewLine( "DOS" ) ); assertEquals( "\n", xmlOutputMeta.getNewLine( "UNIX" ) ); assertEquals( System.getProperty( "line.separator" ), xmlOutputMeta.getNewLine( ...
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) { FunctionConfig mergedConfig = existingConfig.toBuilder().build(); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); ...
@Test public void testMergeEqual() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createFunctionConfig(); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( n...
@Override public void handleReply(Reply reply) { if (failure.get() != null) { return; } if (containsFatalErrors(reply.getErrors())) { failure.compareAndSet(null, new IOException(formatErrors(reply))); return; } long now = System.currentTime...
@Test public void requireThatJson2VespaFeederWorks() throws Throwable { ByteArrayOutputStream dump = new ByteArrayOutputStream(); assertFeed(new FeederParams().setDumpStream(dump).setDumpFormat(FeederParams.DumpFormat.VESPA), "[" + " { \"put\": \"id:simple:si...
@Override public boolean filterPath(Path filePath) { if (getIncludeMatchers().isEmpty() && getExcludeMatchers().isEmpty()) { return false; } // compensate for the fact that Flink paths are slashed final String path = filePath.hasWindowsDrive() ? filePath....
@Test void testIncludeFileWithCharacterRangeMatcher() { GlobFilePathFilter matcher = new GlobFilePathFilter( Collections.singletonList("dir/[a-d].txt"), Collections.emptyList()); assertThat(matcher.filterPath(new Path("dir/a.txt"))).isFalse(); assertT...
public RuntimeOptionsBuilder parse(Class<?> clazz) { RuntimeOptionsBuilder args = new RuntimeOptionsBuilder(); for (Class<?> classWithOptions = clazz; hasSuperClass( classWithOptions); classWithOptions = classWithOptions.getSuperclass()) { CucumberOptions options = requireNonNul...
@Test void create_with_multiple_names() { RuntimeOptions runtimeOptions = parser().parse(MultipleNames.class).build(); List<Pattern> filters = runtimeOptions.getNameFilters(); assertThat(filters.size(), is(equalTo(2))); Iterator<Pattern> iterator = filters.iterator(); asser...
public static ScalarOperator compoundAnd(Collection<ScalarOperator> nodes) { return createCompound(CompoundPredicateOperator.CompoundType.AND, nodes); }
@Test public void compoundAnd2() { ScalarOperator tree1 = Utils.compoundAnd(ConstantOperator.createInt(1), ConstantOperator.createInt(2), ConstantOperator.createInt(3), ConstantOperator.createInt(4)); assertEquals(CompoundPredicateOperator.CompoundTyp...
static AggregationStrategy createAggregationStrategy(CamelContext camelContext, DynamicRouterConfiguration cfg) { AggregationStrategy strategy = Optional.ofNullable(cfg.getAggregationStrategyBean()) .or(() -> Optional.ofNullable(cfg.getAggregationStrategy()) .map(ref -> l...
@Test void testCreateAggregationStrategyNoOp() { when(mockConfig.getAggregationStrategyBean()).thenReturn(null); when(mockConfig.getAggregationStrategy()).thenReturn(null); AggregationStrategy strategy = DynamicRouterRecipientListHelper.createAggregationStrategy(camelContext, mockConfig); ...
public void registryDefaultSampleThreadPoolExecutor() { ApplicationModel applicationModel = collector.getApplicationModel(); if (applicationModel == null) { return; } try { if (this.frameworkExecutorRepository == null) { this.frameworkExecutorRepos...
@Test public void testRegistryDefaultSampleThreadPoolExecutor() throws NoSuchFieldException, IllegalAccessException { Map<String, Object> serverExecutors = new HashMap<>(); Map<String, Object> clientExecutors = new HashMap<>(); ExecutorService serverExecutor = Executors.newFixedThreadPool(...
@Override public InterpreterResult interpret(String sql, InterpreterContext contextInterpreter) { logger.info("Run SQL command '{}'", sql); return executeSql(sql); }
@Test void badSqlSyntaxFails() { InterpreterResult ret = bqInterpreter.interpret(constants.getWrong(), context); assertEquals(InterpreterResult.Code.ERROR, ret.code()); }
@Override public Map<String, ConfigChangeItem> doParse(String oldContent, String newContent, String type) { Map<String, Object> oldMap = Collections.emptyMap(); Map<String, Object> newMap = Collections.emptyMap(); try { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()...
@Test void testComplexYaml() throws IOException { /* * map: * key1: "string" * key2: * - item1 * - item2 * - item3 * key3: 123 */ String s = "map:\n" + " key1: \"string\"\n" + " key2:\n" + " - item1\n" + "...
public void disableNotification() { this.disableNotification = true; }
@Test void comparison() { SendMessage sm1 = SendMessage .builder() .chatId(1L) .text("Hello World") .build(); SendMessage sm2 = SendMessage .builder() .chatId("1") .text("Hello World") ...
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "requiredColumns is ImmutableSet") public Collection<? extends ColumnReferenceExp> get() { return requiredColumns; }
@Test public void shouldRemove() { // Given: builder.addAll(ImmutableSet.of(COL0_REF, COL1_REF, COL2_REF)); // When: builder.remove(COL1_REF); // Then: assertThat(builder.build().get(), is(ImmutableSet.of(COL0_REF, COL2_REF))); }
Future<Boolean> canRoll(int podId) { LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId); return canRollBroker(descriptions, podId); }
@Test public void testNoLeader(VertxTestContext context) { KSB ksb = new KSB() .addNewTopic("A", false) .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1") .addNewPartition(0) .replicaOn(0, 1, 2) /...
public static void setField( final Object object, final String fieldName, final Object fieldNewValue) { try { traverseClassHierarchy( object.getClass(), NoSuchFieldException.class, (InsideTraversal<Void>) traversalClass -> { Field field = trave...
@Test public void setFieldReflectively_setsPrivateFields() { ExampleDescendant example = new ExampleDescendant(); example.overridden = 5; ReflectionHelpers.setField(example, "overridden", 10); assertThat(example.overridden).isEqualTo(10); }
public static String getObjectName(final String upstreamUrl, final String serviceName) { String[] ipAndPort = upstreamUrl.split(":"); return serviceName + "@tcp -h " + ipAndPort[0] + " -p " + ipAndPort[1]; }
@Test public void testGetObjectName() { final String result = PrxInfoUtil.getObjectName("127.0.0.1:8080", "serviceName"); assertEquals("serviceName@tcp -h 127.0.0.1 -p 8080", result); }
@SuppressWarnings("unchecked") @Override public boolean canHandleReturnType(Class returnType) { return rxSupportedTypes.stream() .anyMatch(classType -> classType.isAssignableFrom(returnType)); }
@Test public void testCheckTypes() { assertThat(rxJava2RateLimiterAspectExt.canHandleReturnType(Flowable.class)).isTrue(); assertThat(rxJava2RateLimiterAspectExt.canHandleReturnType(Single.class)).isTrue(); }
public static String getBroadcastAddr(String ipAddr, int prefixLength) { String subnet = ipAddr + "/" + prefixLength; SubnetUtils utils = new SubnetUtils(subnet); return utils.getInfo().getBroadcastAddress(); }
@Test public void testGetBroadcastAddr() { String ipAddr = "192.168.10.35"; int prefix1 = 24; String broadcast1 = getBroadcastAddr(ipAddr, prefix1); assertEquals(broadcast1, "192.168.10.255"); int prefix2 = 28; String broadcast2 = getBroadcastAddr(ipAddr, prefix2); ...
public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException { try { copyBytes(in, out, buffSize); if(close) { out.close(); out = null; in.close(); in = null; } } finally { ...
@Test public void testCopyBytesShouldCloseInputSteamWhenOutputStreamCloseThrowsRunTimeException() throws Exception { InputStream inputStream = Mockito.mock(InputStream.class); OutputStream outputStream = Mockito.mock(OutputStream.class); Mockito.doReturn(-1).when(inputStream).read(new byte[1]); ...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedNoArrowSpaces() { String[] forwardedFields = {" f2 ; f3 ; f0 "}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, forwardedFields, null, null, fiveIntTupleType, fiveI...
static BytecodeExpression lessThan(BytecodeExpression left, BytecodeExpression right) { checkArgumentTypes(left, right); OpCode comparisonInstruction; OpCode noMatchJumpInstruction; Class<?> type = left.getType().getPrimitiveType(); if (type == int.class) { comp...
@Test public void testLessThan() throws Exception { assertBytecodeExpression(lessThan(constantInt(3), constantInt(7)), 3 < 7, "(3 < 7)"); assertBytecodeExpression(lessThan(constantInt(7), constantInt(3)), 7 < 3, "(7 < 3)"); assertBytecodeExpression(lessThan(constantInt(7), co...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithInteger() throws SQLException { int result = 0; when(mergeResultSet.getValue(1, int.class)).thenReturn(result); assertThat(shardingSphereResultSet.getObject(1, int.class), is(result)); when(mergeResultSet.getValue(1, Integer.class)).thenReturn(result); ...
public FilesToken getToken() { return token; }
@Test void sasTokenForCopyPastedURIShouldBePreserved() { var plainToken = "sv=2022-11-02&ss=f&srt=sco&sp=rwdlc&se=2023-05-28T22:50:04Z&st=2023-05-24T14:50:04Z&spr=https&sig=gj%2BUKSiCWSHmcubvGhyJhatkP8hkbXkrmV%2B%2BZme%2BCxI%3D"; // context while resolving endpoint calls SAS setters ...
@Override public KeyValueSegment getOrCreateSegmentIfLive(final long segmentId, final ProcessorContext context, final long streamTime) { final KeyValueSegment segment = super.getOrCreateSegmentIfLive(segm...
@Test public void futureEventsShouldNotCauseSegmentRoll() { updateStreamTimeAndCreateSegment(0); verifyCorrectSegments(0, 1); updateStreamTimeAndCreateSegment(1); verifyCorrectSegments(0, 2); updateStreamTimeAndCreateSegment(2); verifyCorrectSegments(0, 3); up...
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testLoadMoreThan100() throws IllegalAccessException { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); var ctx = setupContext(); var brokerLoadDataStore = ctx.brokerLoadDataStore(); brokerLoadDataS...
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testRemainTimeToLive() { RLock lock = redisson.getLock("test-lock:1"); lock.lock(1, TimeUnit.HOURS); assertThat(lock.remainTimeToLive()).isBetween(TimeUnit.HOURS.toMillis(1) - 10, TimeUnit.HOURS.toMillis(1)); lock.unlock(); assertThat(lock.remainTimeToLive()...
@GetSize public double getSize( @Element SubscriptionPartition subscriptionPartition, @Restriction OffsetByteRange restriction) { if (restriction.getRange().getTo() != Long.MAX_VALUE) { return restriction.getByteCount(); } return newTracker(subscriptionPartition, restriction).getProgress...
@Test public void getProgressUnboundedRangeDelegates() { Progress progress = Progress.from(0, 0.2); when(tracker.getProgress()).thenReturn(progress); assertTrue( DoubleMath.fuzzyEquals( progress.getWorkRemaining(), sdf.getSize(PARTITION, RESTRICTION), .0001)); verify(tracker).getPr...
public static Builder builder() { return new Builder(); }
@Test public void testRoundTripSerDe() throws JsonProcessingException { String fullJson = "{\"identifiers\":[{\"namespace\":[\"accounting\",\"tax\"],\"name\":\"paid\"}],\"next-page-token\":null}"; assertRoundTripSerializesEquallyFrom( fullJson, ListTablesResponse.builder().addAll(IDENTIFIERS)....
public HollowOrdinalIterator findKeysWithPrefix(String prefix) { TST current; HollowOrdinalIterator it; do { current = prefixIndexVolatile; it = current.findKeysWithPrefix(prefix); } while (current != this.prefixIndexVolatile); return it; }
@Test public void testFindKeysWithPrefix() throws Exception { for (Movie movie : getSimpleList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowTokenizedPrefixIndex tokenizedPrefixIndex = new HollowTokeniz...
public static final StartTime relative(Duration relativeStart) { return new StartTime(StartTimeOption.RELATIVE, relativeStart, null); }
@Test public void testStopRelative() { StopTime st = StopTime.relative(Duration.ofMinutes(20)); assertEquals(StopTimeOption.RELATIVE, st.option()); assertEquals(20 * 60, st.relativeTime().getSeconds()); assertNull(st.absoluteTime()); }
public void contains(@Nullable CharSequence string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that contains", string); } else if (!actual.contains(string)) { failWithActual("expected to contain", string); } }
@Test public void stringContains() { assertThat("abc").contains("c"); }
public static IOException maybeExtractIOException( String path, Throwable thrown, String message) { if (thrown == null) { return null; } // walk down the chain of exceptions to find the innermost. Throwable cause = getInnermostThrowable(thrown.getCause(), thrown); // see i...
@Test public void testUnknownHostExceptionExtraction() throws Throwable { final SdkClientException thrown = sdkException("top", sdkException("middle", new UnknownHostException("bottom"))); final IOException ioe = intercept(UnknownHostException.class, "top", () -> { throw ...
public CheckpointManager getCheckpointManager() { return checkpointManager; }
@Test public void testCommitFailedWillRestore() throws Exception { long jobId = instance.getFlakeIdGenerator(Constant.SEATUNNEL_ID_GENERATOR_NAME).newId(); JobMaster jobMaster = newJobInstanceWithRunningState(jobId); // call checkpoint timeout jobMaster .getCheckpoin...
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException { final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest); if (samlRequest instanceof AuthenticationRequest) { dcMetadataResponseMapper.dcMetadataToAuthent...
@Test public void resolveDcMinimumAuthLevelNotFoundTest() throws DienstencatalogusException { DcMetadataResponse dcMetadataResponse = dcClientStubGetMetadata(stubsCaMetadataFile, null, 1L); dcMetadataResponse.setMinimumReliabilityLevel(null); when(dienstencatalogusClientMock.retrieveMetadata...
@Override public void begin(Channels channels) { if (running) { return; } lock.lock(); try { this.allocateBuffer2Thread(); for (ConsumerThread consumerThread : consumerThreads) { consumerThread.start(); } run...
@Test public void testBeginConsumeDriver() { Channels<SampleData> channels = new Channels<SampleData>(2, 100, new SimpleRollingPartitioner<SampleData>(), BufferStrategy.BLOCKING); ConsumeDriver<SampleData> pool = new ConsumeDriver<SampleData>("default", channels, new SampleConsumer(), 2, 20); ...
@SuppressWarnings("deprecation") @Override public Integer call() throws Exception { super.call(); try (var files = Files.walk(directory)) { List<String> flows = files .filter(Files::isRegularFile) .filter(YamlFlowParser::isValidExtension) ...
@Test void runWithDelete() { URL directory = FlowNamespaceUpdateCommandTest.class.getClassLoader().getResource("flows"); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); URL subDirectory = FlowNamespaceUpdateCommandTest.class.getClassLoad...
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testTags() { run("tags.feature"); match(fr.result.getVariables(), "{ configSource: 'normal', functionFromKarateBase: '#notnull', tagNames: ['two=foo,bar', 'one'], tagValues: { one: [], two: ['foo', 'bar'] } }"); }
@Override public BeamSqlTable buildBeamSqlTable(Table table) { return new BigQueryTable(table, getConversionOptions(table.getProperties())); }
@Test public void testSelectDirectReadMethod() { Table table = fakeTableWithProperties( "hello", "{" + METHOD_PROPERTY + ": " + "\"" + Method.DIRECT_READ.toString() + "\" }"); BigQueryTable sqlTable = (BigQueryTable) provider.buildBeamSqlTable(table); assertEquals(Method.DIRECT_READ, ...
public long getLang_id() { return lang_id; }
@Test public void testGetLang_id() { assertEquals(TestParameters.VP_LANGUAGE_ID, chmItspHeader.getLang_id()); }
@Override @MethodNotAvailable public CompletionStage<Boolean> putIfAbsentAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testPutIfAbsentAsync() { adapter.putIfAbsentAsync(23, "newValue"); }
@UdafFactory(description = "Compute average of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint>") public static TableUdaf<Integer, Struct, Double> averageInt() { return getAverageImplementation( 0, STRUCT_INT, (sum, newValue) -> sum.getInt32(SUM) + ne...
@Test public void shouldAverageZeroes() { final TableUdaf<Integer, Struct, Double> udaf = AverageUdaf.averageInt(); Struct agg = udaf.initialize(); final int[] values = new int[] {0, 0, 0}; for (final int thisValue : values) { agg = udaf.aggregate(thisValue, agg); } final double avg = ud...
static <T, R> Function<T, R> decorateFunction(Observation observation, Function<T, R> function) { return (T t) -> observation.observe(() -> function.apply(t)); }
@Test public void shouldDecorateFunctionAndReturnWithSuccess() throws Throwable { given(helloWorldService.returnHelloWorldWithName("Tom")).willReturn("Hello world Tom"); Function<String, String> function = Observations .decorateFunction(observation, helloWorldService::returnHelloWorldWit...
public boolean dropTable(String location) { return dropTable(location, true); }
@Test public void testDropTable() { TABLES.create(SCHEMA, tableDir.toURI().toString()); TABLES.dropTable(tableDir.toURI().toString()); assertThatThrownBy(() -> TABLES.load(tableDir.toURI().toString())) .isInstanceOf(NoSuchTableException.class) .hasMessageStartingWith("Table does not exist...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final Map<Path, List<Long>> regular = new HashMap<>(); final Map<Path, List<Long>> trashed = new HashMap<>(); for(Path file : files.keySet(...
@Test public void testDeleteRecursively() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Pat...
@Restricted(NoExternalUse.class) public boolean isDescendant(String childRelativePath) throws IOException { return false; }
@Test public void testIsDescendant_AbstractBase() throws Exception { VirtualFile root = new VirtualFileMinimalImplementation(); assertFalse(root.isDescendant("anything")); }
public static Builder from(KubevirtNode node) { return new Builder() .hostname(node.hostname()) .clusterName(node.clusterName()) .type(node.type()) .intgBridge(node.intgBridge()) .tunBridge(node.tunBridge()) .managem...
@Test public void testFrom() { KubevirtNode updatedNode = DefaultKubevirtNode.from(refNode).build(); assertEquals(updatedNode, refNode); }
public void incBrokerPutNums() { this.statsTable.get(Stats.BROKER_PUT_NUMS).getAndCreateStatsItem(this.clusterName).getValue().add(1); }
@Test public void testIncBrokerPutNums() { brokerStatsManager.incBrokerPutNums(); assertThat(brokerStatsManager.getStatsItem(BROKER_PUT_NUMS, CLUSTER_NAME).getValue().doubleValue()).isEqualTo(1L); }
@VisibleForTesting CompletableFuture<Acknowledge> getBootstrapCompletionFuture() { return bootstrapCompletionFuture; }
@Test void testClusterShutdownWhenApplicationSucceeds() throws Exception { // we're "listening" on this to be completed to verify that the cluster // is being shut down from the ApplicationDispatcherBootstrap final CompletableFuture<ApplicationStatus> externalShutdownFuture = ...
String currentProject() { String urlString = String.format("%s/computeMetadata/v1/project/project-id", endpoint); return callGet(urlString); }
@Test public void currentProject() { // given stubFor(get(urlEqualTo("/computeMetadata/v1/project/project-id")) .withHeader("Metadata-Flavor", equalTo("Google")) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(PROJECT))); // when ...
public static RpcQosOptions defaultOptions() { return newBuilder().build(); }
@Test public void defaultOptionsBuildSuccessfully() { assertNotNull(RpcQosOptions.defaultOptions()); }
@Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { return super.touch(file, status.withChecksum(write.checksum(file, status).compute(new NullInputStream(0L), status))); }
@Test public void testTouchVirtualHost() throws Exception { final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final S3TouchFeature feature = new S3TouchFeature(virtualhost, acl); final String filename = new AsciiRandomStringService().random(); assertTrue...
@Override public void finished(boolean allStepsExecuted) { if (postProjectAnalysisTasks.length == 0) { return; } ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED); for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) { ...
@Test @UseDataProvider("booleanValues") public void logStatistics_add_fails_when_NPE_if_key_or_value_is_null(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); PostProjectAnalysisTask.LogStatistics logStatistics = tas...
@GET @Produces(MediaType.APPLICATION_JSON) public Response nodes() { log.trace(String.format(MESSAGE_NODE, QUERY)); Set<OpenstackNode> osNodes = osNodeService.nodes(); for (OpenstackNode osNode : osNodes) { osJsonNodes.add(codec(OpenstackNode.class).encode(osNode, this)); ...
@Test public void testGetNodesPopulatedArray() { expect(mockOpenstackNodeService.nodes()). andReturn(ImmutableSet.of(openstackNode)).anyTimes(); replay(mockOpenstackNodeService); final WebTarget wt = target(); final String response = wt.path(PATH).request().get(Strin...
public static Object coerceParameter(Type requiredType, Object valueToCoerce) { return (requiredType != null && valueToCoerce != null) ? actualCoerceParameter(requiredType, valueToCoerce) : valueToCoerce; }
@Test void coerceParameterDateToDateTimeConverted() { Object value = LocalDate.now(); Object retrieved = CoerceUtil.coerceParameter(BuiltInType.DATE_TIME, value); assertNotNull(retrieved); assertTrue(retrieved instanceof ZonedDateTime); ZonedDateTime zdtRetrieved = (ZonedDate...
@Override protected ResultSubpartitionView createSubpartitionView( int subpartitionId, BufferAvailabilityListener availabilityListener) throws IOException { checkState(!isReleased(), "ResultPartition already released."); // If data file is not readable, throw PartitionNotFou...
@Test void testCreateSubpartitionViewLostData() throws Exception { final int numBuffers = 10; BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers); HsResultPartition resultPartition = createHsResultPartition(2, bufferPool); IOUtils.deleteFilesRecursively(tempDa...