focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Entrance public final void combine(@SourceFrom long count) { if (count < this.value) { this.value = count; } }
@Test public void testSelfCombine() { MinLongMetricsImpl impl = new MinLongMetricsImpl(); impl.combine(10); impl.combine(5); MinLongMetricsImpl impl2 = new MinLongMetricsImpl(); impl2.combine(2); impl2.combine(6); impl.combine(impl2); Assertions.asse...
public static Function getFunctionOfRound(FunctionCallExpr node, Function fn, List<Type> argumentTypes) { return getFunctionOfRound(node.getParams(), fn, argumentTypes); }
@Test public void testGetFnOfTruncateForDecimalAndIntLiteral() { List<Expr> params = Lists.newArrayList(); params.add(new DecimalLiteral(new BigDecimal(new BigInteger("1845076"), 2))); params.add(new IntLiteral(1)); FunctionCallExpr node = new FunctionCallExpr(FunctionSet.TRUNCATE, p...
public Optional<ByteBuffer> dequeue() throws QueueException { if (!currentHeadPtr.isGreaterThan(currentTailPtr)) { if (currentTailPtr.isGreaterThan(currentHeadPtr)) { // sanity check throw new QueueException("Current tail " + currentTailPtr + " is forward head " + cur...
@Test public void readFromEmptyQueue() throws QueueException { final QueuePool queuePool = QueuePool.loadQueues(tempQueueFolder, PAGE_SIZE, SEGMENT_SIZE); final Queue queue = queuePool.getOrCreate("test"); assertFalse(queue.dequeue().isPresent(), "Pulling from empty queue MUST return null v...
@Override public OUT nextRecord(OUT record) throws IOException { OUT returnRecord = null; do { returnRecord = super.nextRecord(record); } while (returnRecord == null && !reachedEnd()); return returnRecord; }
@Test void testIntegerFields() { try { final String fileContent = "111|222|333|444|555\n666|777|888|999|000|\n"; final FileInputSplit split = createTempFile(fileContent); final TupleTypeInfo<Tuple5<Integer, Integer, Integer, Integer, Integer>> typeInfo = ...
Set<String> pickMatchingApiDefinitions(ServerWebExchange exchange) { return GatewayApiMatcherManager.getApiMatcherMap().values() .stream() .filter(m -> m.test(exchange)) .map(WebExchangeApiMatcher::getApiName) .collect(Collectors.toSet()); }
@Test public void testPickMatchingApiDefinitions() { // Mock a request. ServerWebExchange exchange = mock(ServerWebExchange.class); ServerHttpRequest request = mock(ServerHttpRequest.class); when(exchange.getRequest()).thenReturn(request); RequestPath requestPath = mock(Reque...
public int remove(long k) { if (k == 0L) { return containsNullKey ? removeNullEntry() : defRetValue; } else { long[] key = this.key; int pos = (int) mix(k) & mask; long curr = key[pos]; if (curr == 0L) { return defR...
@Test public void testRemove() { // Test remove() and get() without rehashing testRemove(10); // Test remove() and get() with rehashing testRemove(1000); }
@Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY, Xoo2.KEY))) { File ioFile = file.file(); File measureFile = new File(ioFile.getParentFile(), ioFile.getName() + MEASURES_EXTENSION); ...
@Test public void failIfMetricNotFound() throws IOException { File measures = new File(baseDir, "src/foo.xoo.measures"); FileUtils.write(measures, "unknow:12\n\n#comment"); InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build(); ...
public static Ip6Address makeMaskPrefix(int prefixLength) { byte[] mask = IpAddress.makeMaskPrefixArray(VERSION, prefixLength); return new Ip6Address(mask); }
@Test(expected = IllegalArgumentException.class) public void testInvalidMakeNegativeMaskPrefixIPv6() { Ip6Address ipAddress; ipAddress = Ip6Address.makeMaskPrefix(-1); }
@Override public void onMsg(TbContext ctx, TbMsg msg) { var tbMsg = ackIfNeeded(ctx, msg); httpClient.processMessage(ctx, tbMsg, m -> tellSuccess(ctx, m), (m, t) -> tellFailure(ctx, m, t)); }
@Test public void deleteRequestWithoutBody() throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final String path = "/path/to/delete"; setupServer("*", new HttpRequestHandler() { @Override public void handle(HttpRequest req...
public Duration queryTimeout() { return queryTimeout; }
@Test void queryTimeoutBadValues() { assertThatExceptionOfType(NullPointerException.class) .isThrownBy(() -> builder.queryTimeout(null)); }
public boolean validate( Policies policies, TimePartitionSpec timePartitioning, TableUri tableUri, String schema) { if (policies != null && policies.getRetention() != null) { // Two invalid case for timePartitioned table if (timePartitioning != null) { if (policies.getRetention().getColum...
@Test void testValidate() { // Negative: declared retention column not exists RetentionColumnPattern pattern0 = RetentionColumnPattern.builder() .pattern("yyyy-mm-dd-hh") .columnName("bb") .build(); /* dummySchema doesn't have bb*/ Retention retention0 = ...
@Deprecated public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { Method method; if (parameterTypes == null) { List<Method> finded = new ArrayList<>(); fo...
@Test void testFindMethodByMethodSignatureOverrideMoreThan1() throws Exception { try { ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", null); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), contain...
@Override public int compareTo(DateTimeStamp dateTimeStamp) { return comparator.compare(this,dateTimeStamp); }
@Test void testCompareEquals() { DateTimeStamp object1 = new DateTimeStamp("2018-04-04T10:10:00.586-0100"); DateTimeStamp object2 = new DateTimeStamp("2018-04-04T10:10:00.586-0100"); assertEquals(0, object1.compareTo(object2)); }
@Override public void destroy() { if (this.producer != null) { try { this.producer.close(); } catch (Exception e) { log.error("Failed to close producer during destroy()", e); } } }
@Test public void givenProducerIsNotNull_whenDestroy_thenShouldClose() { ReflectionTestUtils.setField(node, "producer", producerMock); node.destroy(); then(producerMock).should().close(); }
@Override public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException { final TransferStatus status = super.prepare(file, local, parent, progress); if(status.isExists()) { final String filename...
@Test public void testPrepare() throws Exception { RenameFilter f = new RenameFilter(new DisabledDownloadSymlinkResolver(), new NullTransferSession(new Host(new TestProtocol()))); final String name = new AsciiRandomStringService().random(); final NullLocal local = new NullLocal("/tmp", name)...
@Override public void doRun() { if (versionOverride.isPresent()) { LOG.debug("Elasticsearch version is set manually. Not running check."); return; } final Optional<SearchVersion> probedVersion = this.versionProbe.probe(this.elasticsearchHosts); probedVersion...
@Test void createsNotificationIfCurrentVersionIncompatiblyOlderThanInitialOne() { returnProbedVersion(Version.of(6, 8, 1)); createPeriodical(SearchVersion.elasticsearch(8, 1, 2)).doRun(); assertNotificationWasRaised(); }
@Override @MethodNotAvailable public CompletionStage<Boolean> deleteAsync(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testDeleteAsync() { adapter.deleteAsync(23); }
@Override public Set<ConfigOption<?>> requiredOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(USERNAME); options.add(PASSWORD); options.add(DATABASE_NAME); options.add(TABLE_NAME); options.add(SCHEMA_NAME); return options; }
@Test public void testValidation() { // validate illegal port try { Map<String, String> properties = getAllRequiredOptionsWithHost(); properties.put("port", "123b"); createTableSource(properties); fail("exception expected"); } catch (Throwable...
public Type getType() { return type; }
@Test public void shouldReturnType() { // Given: final TableElement element = new TableElement(NAME, new Type(SqlTypes.STRING)); // Then: assertThat(element.getType(), is(new Type(SqlTypes.STRING))); }
public final String getName() { return getEnvironment().getTaskInfo().getTaskNameWithSubtasks(); }
@Test void testStateBackendClosingOnFailure() throws Exception { Configuration taskManagerConfig = new Configuration(); taskManagerConfig.set(STATE_BACKEND, TestMemoryStateBackendFactory.class.getName()); StreamConfig cfg = new StreamConfig(new Configuration()); cfg.setStateKeySeria...
@Override public SparkTable loadTable(Identifier ident) throws NoSuchTableException { Pair<Table, Long> table = load(ident); return new SparkTable(table.first(), table.second(), false /* refresh eagerly */); }
@Test public void testTimeTravel() { sql("CREATE TABLE %s (id INT, dep STRING) USING iceberg", tableName); Table table = validationCatalog.loadTable(tableIdent); sql("INSERT INTO TABLE %s VALUES (1, 'hr')", tableName); table.refresh(); Snapshot firstSnapshot = table.currentSnapshot(); waitU...
@Override public boolean add(String e) { return get(addAsync(e)); }
@Test public void testRandom() { RLexSortedSet al = redisson.getLexSortedSet("test"); for (int i = 0; i < 100; i++) { al.add("" + i); } Set<String> values = new HashSet<>(); for (int i = 0; i < 3; i++) { String v = al.random(); values.add(...
@Override public Optional<FunctionDefinition> getFunctionDefinition(String name) { if (BUILT_IN_FUNC_BLACKLIST.contains(name)) { return Optional.empty(); } FunctionDefinitionFactory.Context context = () -> classLoader; // We override some Hive's function by native implem...
@Test public void testHiveBuiltInFunction() { FunctionDefinition fd = new HiveModule().getFunctionDefinition("reverse").get(); HiveSimpleUDF udf = (HiveSimpleUDF) fd; DataType[] inputType = new DataType[] {DataTypes.STRING()}; CallContextMock callContext = new CallContextMock(); ...
@Override public boolean containsAll(IntSet set) { return set.isEmpty(); }
@Test public void testContainsAll() throws Exception { IntSet sis2 = new SingletonIntSet(3); assertFalse(es.containsAll(sis2)); assertTrue(sis2.containsAll(es)); IntSet sis3 = new RangeSet(0); assertTrue(sis3.containsAll(es)); assertTrue(es.containsAll(sis3)); }
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_describe_all_tables() { // Given String query = "DESCRIBE TABLES;"; final String expected = reformatHtml(readTestResource( "/scalate/DescribeTables.html")); // When final InterpreterResult actual = interpreter.interpret(query, intrContext); // Then assertEquals(...
public static MetricsSource makeSource(Object source) { return new MetricsSourceBuilder(source, DefaultMetricsFactory.getAnnotatedMetricsFactory()).build(); }
@Test public void testMethods() { MyMetrics2 metrics = new MyMetrics2(); MetricsSource source = MetricsAnnotations.makeSource(metrics); MetricsRecordBuilder rb = getMetrics(source); verify(rb).addGauge(info("G1", "G1"), 1); verify(rb).addGauge(info("G2", "G2"), 2L); verify(rb).addGauge(info("G3...
@Override public Result run(GoPluginDescriptor pluginDescriptor, Map<String, List<String>> extensionsInfoOfPlugin) { final ValidationResult validationResult = validate(pluginDescriptor, extensionsInfoOfPlugin); return new Result(validationResult.hasError(), validationResult.toErrorMessage()); }
@Test void shouldNotAddErrorOnSuccessfulValidation() { final PluginPostLoadHook.Result validationResult = pluginExtensionsAndVersionValidator.run(descriptor, Map.of(ELASTIC_AGENT_EXTENSION, List.of("2.0"))); assertThat(validationResult.isAFailure()).isFalse(); assertThat(validationResult.ge...
public synchronized void rewind() { this.readPosition = 0; this.curReadBufferIndex = 0; this.readPosInCurBuffer = 0; if (CollectionUtils.isNotEmpty(bufferList)) { this.curBuffer = bufferList.get(0); for (ByteBuffer buffer : bufferList) { buffer.rew...
@Test public void testCommitLogTypeInputStreamWithCoda() { List<ByteBuffer> uploadBufferList = new ArrayList<>(); int bufferSize = 0; for (int i = 0; i < MSG_NUM; i++) { ByteBuffer byteBuffer = MessageFormatUtilTest.buildMockedMessageBuffer(); uploadBufferList.add(byt...
public String[] getTypes() { List<String> types = new ArrayList<>(); for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) { types.add( runConfigurationProvider.getType() ); } return types.toArray( new String[ 0 ] ); }
@Test public void testGetTypes() { String[] types = executionConfigurationManager.getTypes(); assertTrue( Arrays.asList( types ).contains( DefaultRunConfiguration.TYPE ) ); }
@Override public LeaderElection createLeaderElection(String componentId) { synchronized (lock) { Preconditions.checkState( !leadershipOperationExecutor.isShutdown(), "The service was already closed and cannot be reused."); Preconditions.checkSt...
@Test void testMultipleDriverCreations() throws Exception { final AtomicInteger closeCount = new AtomicInteger(0); final TestingLeaderElectionDriver.Factory driverFactory = new TestingLeaderElectionDriver.Factory( TestingLeaderElectionDriver.newNoOpBuilder() ...
public TagList getStepInstanceTags( String workflowId, long workflowInstanceId, long workflowRunId, String stepId, String stepAttempt) { return getStepInstanceFieldByIds( StepInstanceField.INSTANCE, workflowId, workflowInstanceId, workflowRunId, ...
@Test public void testGetStepInstanceTags() { TagList tags = stepDao.getStepInstanceTags(TEST_WORKFLOW_ID, 1, 1, "job1", "1"); assertEquals(si.getTags(), tags); TagList latest = stepDao.getStepInstanceTags(TEST_WORKFLOW_ID, 1, 1, "job1", "latest"); assertEquals(tags, latest); }
@Nullable public Span next(TraceContextOrSamplingFlags extracted) { Tracer tracer = tracer(); if (tracer == null) return null; Span next = tracer.nextSpan(extracted); SpanAndScope spanAndScope = new SpanAndScope(next, tracer.withSpanInScope(next)); getCurrentSpanInScopeStack().addFirst(spanAndScope)...
@Test void next() { assertThat(threadLocalSpan.next()) .isEqualTo(threadLocalSpan.remove()); }
public PostgreSQLPacket describe() { if (responseHeader instanceof QueryResponseHeader) { return createRowDescriptionPacket((QueryResponseHeader) responseHeader); } if (responseHeader instanceof UpdateResponseHeader) { return PostgreSQLNoDataPacket.getInstance(); ...
@Test void assertDescribeBeforeBind() { PostgreSQLServerPreparedStatement preparedStatement = mock(PostgreSQLServerPreparedStatement.class); when(preparedStatement.getSqlStatementContext()).thenReturn(mock(SQLStatementContext.class)); assertThrows(IllegalStateException.class, () -> new Porta...
@Deprecated @Override public void toXML(Object obj, OutputStream out) { super.toXML(obj, out); }
@Test public void marshalValue() { Foo f = new Foo(); f.r1 = f.r2 = Result.FAILURE; String xml = Run.XSTREAM.toXML(f); // we should find two "FAILURE"s as they should be written out twice assertEquals(xml, 3, xml.split("FAILURE").length); }
private List<Integer> getBeSeqIndexes(List<Long> flatBackendsPerBucketSeq, long beId) { return IntStream.range(0, flatBackendsPerBucketSeq.size()).boxed().filter( idx -> flatBackendsPerBucketSeq.get(idx).equals(beId)).collect(Collectors.toList()); }
@Test public void testGetBeSeqIndexes() { List<Long> flatBackendsPerBucketSeq = Lists.newArrayList(1L, 2L, 2L, 3L, 4L, 2L); List<Integer> indexes = Deencapsulation.invoke(balancer, "getBeSeqIndexes", flatBackendsPerBucketSeq, 2L); Assert.assertArrayEquals(new int[] {1, 2, 5},...
@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 testCsv() { run("csv.feature"); }
public void untrackAll(JobID jobId) { checkNotNull(jobId); synchronized (lock) { Set<BlobKey> keysToRemove = blobKeyByJob.remove(jobId); if (keysToRemove != null) { for (BlobKey key : keysToRemove) { untrack(jobId, key); } ...
@Test void testUntrackAll() { tracker.track(jobId, BlobKey.createKey(BlobType.PERMANENT_BLOB), 1L); JobID anotherJobId = new JobID(); tracker.track(anotherJobId, BlobKey.createKey(BlobType.PERMANENT_BLOB), 1L); assertThat(tracker.getBlobKeysByJobId(jobId)).hasSize(2); track...
public static DataMap convertMap(Map<String, ?> input, boolean stringify) { return convertMap(input, false, stringify); }
@Test void testConvertDroppingNulls() { DataMap parent = DataComplexUtil.convertMap(inputMap()); Assert.assertNotNull(parent); Assert.assertEquals(parent.size(), 2); Assert.assertFalse(parent.containsKey("child1")); Assert.assertTrue(parent.containsKey("child2")); DataMap child2 = parent....
public static UParens create(UExpression expression) { return new AutoValue_UParens(expression); }
@Test public void match() { assertUnifies("(5L)", UParens.create(ULiteral.longLit(5L))); }
public SpillSpaceTracker(DataSize maxSize) { requireNonNull(maxSize, "maxSize is null"); maxBytes = maxSize.toBytes(); currentBytes = 0; }
@Test public void testSpillSpaceTracker() { assertEquals(spillSpaceTracker.getCurrentBytes(), 0); assertEquals(spillSpaceTracker.getMaxBytes(), MAX_DATA_SIZE.toBytes()); long reservedBytes = new DataSize(5, MEGABYTE).toBytes(); spillSpaceTracker.reserve(reservedBytes); as...
@Override public boolean isEmpty() { return commandTopic.getEndOffset() == 0; }
@Test public void shouldComputeEmptyCorrectly() { // Given: when(commandTopic.getEndOffset()).thenReturn(0L); // When/Then: assertThat(commandStore.isEmpty(), is(true)); }
@Override public void unbindSocialUser(Long userId, Integer userType, Integer socialType, String openid) { // 获得 openid 对应的 SocialUserDO 社交用户 SocialUserDO socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, openid); if (socialUser == null) { throw exception(SOCIAL_USE...
@Test public void testUnbindSocialUser_notFound() { // 调用,并断言 assertServiceException( () -> socialUserService.unbindSocialUser(randomLong(), UserTypeEnum.ADMIN.getValue(), SocialTypeEnum.GITEE.getType(), "test_openid"), SOCIAL_USER_NOT_FOUND); ...
public static <T> VerboseCondition<T> verboseCondition(Predicate<T> predicate, String description, Function<T, String> objectUnderTestDescriptor) { return new VerboseCondition<>(predicate, description, objectUnderTestDescriptor); }
@Test public void should_fail_and_display_actual_description_as_per_transformation_function_with_hasCondition() { // GIVEN Condition<String> shortLength = verboseCondition(actual -> actual.length() < 4, "length shorter than 4", ...
@Override public boolean isUserManaged(DbSession dbSession, String userUuid) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.isUserManaged(dbSession, userUuid)) .orElse(false); }
@Test public void isUserManaged_whenNoDelegates_returnsFalse() { DelegatingManagedServices managedInstanceService = new DelegatingManagedServices(Set.of()); assertThat(managedInstanceService.isUserManaged(dbSession, "whatever")).isFalse(); }
@Override public String name() { return "ControllerRegistrationsPublisher"; }
@Test public void testName() { ControllerRegistrationsPublisher publisher = new ControllerRegistrationsPublisher(); assertEquals("ControllerRegistrationsPublisher", publisher.name()); }
public void publishUpdated(Cache<K, V> cache, K key, V oldValue, V newValue) { publish(cache, EventType.UPDATED, key, /* hasOldValue */ true, oldValue, newValue, /* quiet */ false); }
@Test public void publishUpdated() { var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run); registerAll(dispatcher); dispatcher.publishUpdated(cache, 1, 2, 3); verify(updatedListener, times(4)).onUpdated(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispa...
public static void notBlank(String str, String message) { if (StringUtil.isBlank(str)) { throw new IllegalArgumentException(message); } }
@Test(expected = IllegalArgumentException.class) public void assertNotBlankByStringAndMessageIsNull() { Assert.notBlank(" "); }
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator464() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); String fileNAK = "file://bad ^ domain.com/label/test"; assertFalse(fileNAK, urlValidator.isValid(fileNAK)); }
@Override public Num getValue(int index) { return getBarSeries().getBar(index).getLowPrice(); }
@Test public void indicatorShouldRetrieveBarLowPrice() { for (int i = 0; i < 10; i++) { assertEquals(lowPriceIndicator.getValue(i), barSeries.getBar(i).getLowPrice()); } }
@Nonnull static String shortenPathComponent(@Nonnull String pathComponent, int bytesToRemove) { // We replace the removed part with a #, so we need to remove 1 extra char bytesToRemove++; int[] codePoints; try { IntBuffer intBuffer = ByteBuffer.wrap(pathComponent.getByte...
@Test public void test2ByteEncodings() { StringBuilder sb = new StringBuilder(); for (int i=0x80; i<0x80+100; i++) { sb.append((char)i); } // remove a total of 3 2-byte characters, and then add back in the 1-byte '#' String result = ClassFileNameHandler.shortenPa...
@Override public Output run(RunContext runContext) throws Exception { URI from = new URI(runContext.render(this.from)); final PebbleExpressionPredicate predicate = getExpressionPredication(runContext); final Path path = runContext.workingDir().createTempFile(".ion"); long processe...
@Test void shouldFilterGivenInvalidRecordsForExclude() throws Exception { // Given RunContext runContext = runContextFactory.of(); FilterItems task = FilterItems .builder() .from(generateKeyValueFile(TEST_INVALID_ITEMS, runContext).toString()) .filterCond...
@Override public List<TableIdentifier> listTables(Namespace namespace) { Preconditions.checkArgument( namespace.levels().length >= 1, "Missing database in table identifier: %s", namespace); Path nsPath = new Path(warehouseLocation, SLASH.join(namespace.levels())); Set<TableIdentifier> tblIdents =...
@Test public void testListTables() throws Exception { HadoopCatalog catalog = hadoopCatalog(); TableIdentifier tbl1 = TableIdentifier.of("db", "tbl1"); TableIdentifier tbl2 = TableIdentifier.of("db", "tbl2"); TableIdentifier tbl3 = TableIdentifier.of("db", "ns1", "tbl3"); TableIdentifier tbl4 = T...
@Override public BasicTypeDefine<MysqlType> reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.<MysqlType>builder() .name(column.getName()) .nullable(column.isNullable()) .comment...
@Test public void testReconvertNull() { Column column = PhysicalColumn.of("test", BasicType.VOID_TYPE, (Long) null, true, "null", "null"); BasicTypeDefine<MysqlType> typeDefine = MySqlTypeConverter.DEFAULT_INSTANCE.reconvert(column); Assertions.assertEquals(c...
public RetriableCommand(String description) { this.description = description; }
@Test public void testRetriableCommand() { try { new MyRetriableCommand(5).execute(0); Assert.assertTrue(false); } catch (Exception e) { Assert.assertTrue(true); } try { new MyRetriableCommand(3).execute(0); Assert.assertTrue(true); } catch (Exception e) { ...
public void displayGiant(GiantModel giant) { LOGGER.info(giant.toString()); }
@Test void testDisplayGiant() { final var view = new GiantView(); final var model = mock(GiantModel.class); view.displayGiant(model); assertEquals(model.toString(), appender.getLastMessage()); assertEquals(1, appender.getLogSize()); }
@Udf public String ucase( @UdfParameter(description = "The string to upper-case") final String input) { if (input == null) { return null; } return input.toUpperCase(); }
@Test public void shouldRetainLowerCaseInput() { final String result = udf.ucase("FOO"); assertThat(result, is("FOO")); }
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testresetPositionsSkipsBlackedOutConnections() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.EARLIEST); // Check that we skip sending the ListOffset request when the node is blacked out client.up...
public static void replaceNodeText(Document document, String containerNodeName, String nodeName, String toReplace, String replacement) { asStream(document.getElementsByTagName(containerNodeName)) .forEach(containerNode -> asStream(containerNode.getChildNodes()) .filter(ch...
@Test public void replaceNodeText() throws Exception { final String replacement = "replacement"; Document document = DOMParserUtil.getDocument(XML); DOMParserUtil.replaceNodeText(document, MAIN_NODE, TEST_NODE, TEST_NODE_CONTENT, replacement); final Map<Node, List<Node>> retrieved = ...
@Override public Map<String, Integer> getRefByUuid() { return refByUuid; }
@Test public void getAll_returns_empty_set() { assertThat(underTest.getRefByUuid()).isEmpty(); }
@VisibleForTesting static boolean isReaperThreadRunning() { synchronized (REAPER_THREAD_LOCK) { return null != REAPER_THREAD && REAPER_THREAD.isAlive(); } }
@Test void testReaperThreadStartFailed() throws Exception { try { new SafetyNetCloseableRegistry(OutOfMemoryReaperThread::new); } catch (java.lang.OutOfMemoryError error) { } assertThat(SafetyNetCloseableRegistry.isReaperThreadRunning()).isFalse(); // the OOM er...
@Override public synchronized ListenableFuture<BufferResult> get(OutputBufferId bufferId, long startSequenceId, DataSize maxSize) { requireNonNull(bufferId, "outputBufferId is null"); checkArgument(bufferId.getId() == outputBufferId.getId(), "Invalid buffer id"); checkArgument(maxSize.to...
@Test public void testMultiplePendingReads() { SpoolingOutputBuffer buffer = createSpoolingOutputBuffer(); // attempt to get a page ListenableFuture<BufferResult> oldPendingRead = buffer.get(BUFFER_ID, 0, sizeOfPages(3)); assertFalse(oldPendingRead.isDone()); Listenable...
@Override public TopicAssignment place( PlacementSpec placement, ClusterDescriber cluster ) throws InvalidReplicationFactorException { RackList rackList = new RackList(random, cluster.usableBrokers()); throwInvalidReplicationFactorIfNonPositive(placement.numReplicas()); t...
@Test public void testRackListNonPositiveReplicationFactor() { MockRandom random = new MockRandom(); RackList rackList = new RackList(random, Arrays.asList( new UsableBroker(11, Optional.of("1"), false), new UsableBroker(10, Optional.of("1"), false)).iterator()); ...
public static List<String> filterTopics(List<String> original, String regex) { Pattern topicsPattern = Pattern.compile(regex); return filterTopics(original, topicsPattern); }
@Test public void testFilterTopics() { String topicName1 = "persistent://my-property/my-ns/pattern-topic-1"; String topicName2 = "persistent://my-property/my-ns/pattern-topic-2"; String topicName3 = "persistent://my-property/my-ns/hello-3"; String topicName4 = "non-persistent://my-pr...
public TableRecords() { }
@Test public void testTableRecords() { Assertions.assertThrows(ShouldNeverHappenException.class, () -> { TableRecords tableRecords = new TableRecords(new TableMeta()); tableRecords.setTableMeta(new TableMeta()); }); TableRecords tableRecords = new TableRecords(new T...
public abstract byte[] encode(MutableSpan input);
@Test void localSpan_JSON_V2() { assertThat(new String(encoder.encode(localSpan), UTF_8)) .isEqualTo( "{\"traceId\":\"dc955a1d4768875d\",\"id\":\"dc955a1d4768875d\",\"name\":\"encode\",\"timestamp\":1510256710021866,\"duration\":1117,\"localEndpoint\":{\"serviceName\":\"isao01\",\"ipv4\":\"10.23...
public static List<Global> getVariableList( final List<String> variableCells ){ final List<Global> variableList = new ArrayList<>(); if ( variableCells == null ) { return variableList; } for( String variableCell: variableCells ){ final StringTokenizer tokens = ne...
@Test public void testBadVariableFormat() { List<String> varCells = List.of("class1, object2"); assertThatExceptionOfType(DecisionTableParseException.class).isThrownBy(() -> getVariableList(varCells)); }
@VisibleForTesting static CPUResource getDefaultCpus(final Configuration configuration) { int fallback = configuration.get(YarnConfigOptions.VCORES); double cpuCoresDouble = TaskExecutorProcessUtils.getCpuCoresWithFallback(configuration, fallback) .getValue() ...
@Test void testGetCpuRoundUp() { final Configuration configuration = new Configuration(); configuration.set(TaskManagerOptions.CPU_CORES, 0.5); assertThat(YarnWorkerResourceSpecFactory.getDefaultCpus(configuration)) .isEqualTo(new CPUResource(1.0)); }
public static void runner(Bank bank, CountDownLatch latch) { try { SecureRandom random = new SecureRandom(); Thread.sleep(random.nextInt(1000)); LOGGER.info("Start transferring..."); for (int i = 0; i < 1000000; i++) { bank.transfer(random.nextInt(4), random.nextInt(4), random.nextIn...
@Test void runnerShouldExecuteWithoutException() { var bank = new Bank(4, 1000); var latch = new CountDownLatch(1); assertDoesNotThrow(() -> Main.runner(bank, latch)); assertEquals(0, latch.getCount()); }
public Type parse(final String schema) { try { final TypeContext typeContext = parseTypeContext(schema); return getType(typeContext); } catch (final ParsingException e) { throw new KsqlStatementException( "Failed to parse schema", "Failed to parse: " + schema, sch...
@Test public void shouldGetTypeFromStruct() { // Given: final String schemaString = "STRUCT<A VARCHAR>"; // When: final Type type = parser.parse(schemaString); // Then: assertThat(type, is(new Type(SqlTypes.struct().field("A", SqlTypes.STRING).build()))); }
public FEELFnResult<TemporalAmount> invoke(@ParameterName( "from" ) String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } try { // try to parse as days/hours/minute/seconds retu...
@Test void invokeParamTemporalPeriod() { FunctionTestUtil.assertResult(durationFunction.invoke(ComparablePeriod.parse("P2Y3M4D")), ComparablePeriod.of(2, 3, 4)); }
void removeActivity(Activity activity) { if (activity != null) { hashSet.remove(activity.hashCode()); } }
@Test public void removeActivity() { mActivityLifecycle.removeActivity(mActivity); }
@Override public Schema getSourceSchema() { if (schema == null) { try { Schema.Parser parser = new Schema.Parser(); schema = parser.parse(schemaString); } catch (Exception e) { throw new HoodieSchemaException("Failed to parse schema: " + schemaString, e); } } ret...
@Test public void validateDefaultSchemaGeneration() throws IOException { TypedProperties properties = new TypedProperties(); properties.setProperty(ProtoClassBasedSchemaProviderConfig.PROTO_SCHEMA_CLASS_NAME.key(), Sample.class.getName()); ProtoClassBasedSchemaProvider protoToAvroSchemaProvider = new Prot...
String getProfileViewResponseFromBody(String responseBody) { String template = (String) DEFAULT_GSON.fromJson(responseBody, Map.class).get("template"); if (StringUtils.isBlank(template)) { throw new RuntimeException("Template was blank!"); } return template; }
@Test public void shouldUnJSONizeGetProfileViewResponseFromBody() { String template = new ElasticAgentExtensionConverterV5().getProfileViewResponseFromBody("{\"template\":\"foo\"}"); assertThat(template, is("foo")); }
@Override public ProjectRepositories load(String projectKey, @Nullable String branchBase) { GetRequest request = new GetRequest(getUrl(projectKey, branchBase)); try (WsResponse response = wsClient.call(request)) { try (InputStream is = response.contentStream()) { return processStream(is); ...
@Test(expected = IllegalStateException.class) public void failFastHttpError() { HttpException http = new HttpException("url", 403, null); IllegalStateException e = new IllegalStateException("http error", http); WsTestUtil.mockException(wsClient, e); loader.load(PROJECT_KEY, null); }
@Override public SendResult send(final Message message) { return send(message, this.rocketmqProducer.getSendMsgTimeout()); }
@Test public void testSend_OK() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { SendResult sendResult = new SendResult(); sendResult.setMsgId("TestMsgID"); sendResult.setSendStatus(SendStatus.SEND_OK); when(rocketmqProducer.send(any(Message.clas...
public static String[] splitString( String string, String separator ) { /* * 0123456 Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<>(); if ( string == null || string.length() == 0 ) {...
@Test public void testSplitStringWithDelimiterNullAndEnclosureNull() { String stringToSplit = "Hello, world"; String[] result = Const.splitString( stringToSplit, null, null ); assertSplit( result, stringToSplit ); }
public static NetworkEndpoint forIp(String ipAddress) { checkArgument(InetAddresses.isInetAddress(ipAddress), "'%s' is not an IP address.", ipAddress); return NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.IP) .setIpAddress( IpAddress.newBuilder() .setAdd...
@Test public void forIp_withIpV6Address_returnsIpV6NetworkEndpoint() { assertThat(NetworkEndpointUtils.forIp("3ffe::1")) .isEqualTo( NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.IP) .setIpAddress( IpAddress.newBuilder() ...
public static TypeDescriptor javaTypeForFieldType(FieldType fieldType) { switch (fieldType.getTypeName()) { case LOGICAL_TYPE: // TODO: shouldn't we handle this differently? return javaTypeForFieldType(fieldType.getLogicalType().getBaseType()); case ARRAY: return TypeDescriptors....
@Test public void testRowTypeToJavaType() { assertEquals( TypeDescriptors.lists(TypeDescriptors.rows()), FieldTypeDescriptors.javaTypeForFieldType( FieldType.array(FieldType.row(Schema.builder().build())))); }
@Override public FindCoordinatorRequest.Builder buildRequest(Set<CoordinatorKey> keys) { unrepresentableKeys = keys.stream().filter(k -> k == null || !isRepresentableKey(k.idValue)).collect(Collectors.toSet()); Set<CoordinatorKey> representableKeys = keys.stream().filter(k -> k != null && isRepresen...
@Test public void testBuildLookupRequestRequiresKeySameType() { CoordinatorStrategy strategy = new CoordinatorStrategy(CoordinatorType.GROUP, new LogContext()); assertThrows(IllegalArgumentException.class, () -> strategy.buildRequest( new HashSet<>(Arrays.asList( ...
@Override public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { final BrickApiClient client = new BrickApiClient(session); if(status.isExists()) { ...
@Test public void testRename() throws Exception { final Path test = new BrickTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random().toLowerCase(), EnumSet.of(Path.Type.file)), new TransferStatus()); final Path...
@Override @MethodNotAvailable public CompletionStage<Void> setAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testSetAsyncWithExpiryPolicy() { ExpiryPolicy expiryPolicy = new HazelcastExpiryPolicy(1, 1, 1, TimeUnit.MILLISECONDS); adapter.setAsync(42, "value", expiryPolicy); }
@Override public String toString() { return "SingleColumn{" + ", alias=" + alias + ", expression=" + expression + '}'; }
@Test public void shouldCreateSingleColumn() { // When: SingleColumn col = new SingleColumn(A_LOCATION, AN_EXPRESSION, Optional.of(WINDOWSTART_NAME)); // Then: assertThat(col.toString(), containsString("SingleColumn{, alias=Optional[`WINDOWSTART`], expression='foo'}")); }
public final void register(Class type, Serializer serializer) { if (type == null) { throw new IllegalArgumentException("type is required"); } if (serializer.getTypeId() <= 0) { throw new IllegalArgumentException( "Type ID must be positive. Current: " +...
@Test(expected = IllegalArgumentException.class) public void testRegister_typeIdNegative() { StringBufferSerializer serializer = new StringBufferSerializer(true); serializer.typeId = -10000; abstractSerializationService.register(StringBuffer.class, serializer); }
public synchronized void write(Mutation tableRecord) throws IllegalStateException { write(ImmutableList.of(tableRecord)); }
@Test public void testWriteMultipleRecordsShouldThrowExceptionWhenSpannerWriteFails() throws ExecutionException, InterruptedException { // arrange prepareTable(); when(spanner.getDatabaseClient(any()).write(any())).thenThrow(SpannerException.class); ImmutableList<Mutation> testMutations = ...
public List<B2FileInfoResponse> find(final Path file) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("Finding multipart uploads for %s", file)); } try { final List<B2FileInfoResponse> uploads = new ArrayList<B2FileInfoResponse>(); ...
@Test public void testFindAllPendingInBucket() throws Exception { final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final B2VersionIdProvider fileid ...
@Override public String getMethod() { return PATH; }
@Test public void testSetMyCommandsWithEmptyStringLanguageCode() { SetMyCommands setMyCommands = SetMyCommands .builder() .command(BotCommand.builder().command("test").description("Test description").build()) .languageCode("") .scope(BotCommand...
@Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ImplicitLinkedHashCollection)) return false; ImplicitLinkedHashCollection<?> ilhs = (ImplicitLinkedHashCollection<?>) o; return this.valuesList().equals(ilhs.valuesLis...
@Test public void testEquals() { ImplicitLinkedHashCollection<TestElement> coll1 = new ImplicitLinkedHashCollection<>(); coll1.add(new TestElement(1)); coll1.add(new TestElement(2)); coll1.add(new TestElement(3)); ImplicitLinkedHashCollection<TestElement> coll2 = new Implici...
public static Pair<Optional<Method>, Optional<TypedExpression>> resolveMethodWithEmptyCollectionArguments( final MethodCallExpr methodExpression, final MvelCompilerContext mvelCompilerContext, final Optional<TypedExpression> scope, List<TypedExpression> arguments, ...
@Test public void resolveMethodWithEmptyCollectionArgumentsMethodExpressionIsNull() { Assertions.assertThatThrownBy( () -> MethodResolutionUtils.resolveMethodWithEmptyCollectionArguments( null, null, ...
@VisibleForTesting public void validateNoticeExists(Long id) { if (id == null) { return; } NoticeDO notice = noticeMapper.selectById(id); if (notice == null) { throw exception(NOTICE_NOT_FOUND); } }
@Test public void testValidateNoticeExists_success() { // 插入前置数据 NoticeDO dbNotice = randomPojo(NoticeDO.class); noticeMapper.insert(dbNotice); // 成功调用 noticeService.validateNoticeExists(dbNotice.getId()); }
public static Map<String, Collection<String>> caseInsensitiveCopyOf(Map<String, Collection<String>> map) { if (map == null) { return Collections.emptyMap(); } Map<String, Collection<String>> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, Collection<String>>...
@Test void caseInsensitiveCopyOfMap() { // Arrange Map<String, Collection<String>> sourceMap = new HashMap<>(); sourceMap.put("First", Arrays.asList("abc", "qwerty", "xyz")); sourceMap.put("camelCase", Collections.singleton("123")); // Act Map<String, Collection<String>> actualMap = caseInsen...
public <T> void compareSupplierResult(final T expected, final Supplier<T> experimentSupplier) { final Timer.Sample sample = Timer.start(); try { final T result = experimentSupplier.get(); recordResult(expected, result, sample); } catch (final Exception e) { recordError(e, sample); } ...
@Test void compareSupplierResultMatch() { experiment.compareSupplierResult(12, () -> 12); verify(matchTimer).record(anyLong(), eq(TimeUnit.NANOSECONDS)); }
@Nullable @Override public String getMainClassFromJarPlugin() { Jar jarTask = (Jar) project.getTasks().findByName("jar"); if (jarTask == null) { return null; } Object value = jarTask.getManifest().getAttributes().get("Main-Class"); if (value instanceof Provider) { value = ((Provide...
@Test public void testGetMainClassFromJarAsProperty_success() { Property<String> mainClass = project.getObjects().property(String.class).value("some.main.class"); Jar jar = project.getTasks().withType(Jar.class).getByName("jar"); jar.setManifest(new DefaultManifest(null).attributes(ImmutableMap.o...
Integer getMaxSize( Collection<BeanInjectionInfo.Property> properties, Object obj ) { int max = Integer.MIN_VALUE; for ( BeanInjectionInfo.Property property: properties ) { max = Math.max( max, ( isCollection( property ) ? getCollectionSize( property, obj ) // if not collectio...
@Test public void getMaxSize_OnlyOneField() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); MetaBeanLevel1 mbl1 = new MetaBeanLevel1(); mbl1.setSub( new MetaBeanLevel2() ); mbl1.getSub().setSeparator( "/" ); assertEquals(new ...
public DropSourceCommand create(final DropStream statement) { return create( statement.getName(), statement.getIfExists(), statement.isDeleteTopic(), DataSourceType.KSTREAM ); }
@Test public void shouldCreateDropSourceOnMissingSourceWithIfExistsForStream() { // Given: final DropStream dropStream = new DropStream(SOME_NAME, true, true); when(metaStore.getSource(SOME_NAME)).thenReturn(null); // When: final DropSourceCommand cmd = dropSourceFactory.create(dropStream); ...
public void run() { try { InputStreamReader isr = new InputStreamReader( this.is ); BufferedReader br = new BufferedReader( isr ); String line = null; while ( ( line = br.readLine() ) != null ) { String logEntry = this.type + " " + line; switch ( this.logLevel ) { c...
@Test public void testLogDebug() { streamLogger = new ConfigurableStreamLogger( log, is, LogLevel.DEBUG, PREFIX ); streamLogger.run(); Mockito.verify( log ).logDebug( OUT1 ); Mockito.verify( log ).logDebug( OUT2 ); }
@Override protected int getJDBCPort() { return DefaultMSSQLServerContainer.MS_SQL_SERVER_PORT; }
@Test public void testGetJDBCPortReturnsCorrectValue() { assertThat(testManager.getJDBCPort()) .isEqualTo(MSSQLResourceManager.DefaultMSSQLServerContainer.MS_SQL_SERVER_PORT); }
@VisibleForTesting KsqlConfig buildConfigWithPort() { final Map<String, Object> props = ksqlConfigNoPort.originals(); // Wire up KS IQ so that pull queries work across KSQL nodes: props.put( KsqlConfig.KSQL_STREAMS_PREFIX + StreamsConfig.APPLICATION_SERVER_CONFIG, restConfig.getInterNodeL...
@Test public void shouldConfigureIQWithInterNodeListenerIfSet() { // Given: givenAppWithRestConfig( ImmutableMap.of( KsqlRestConfig.LISTENERS_CONFIG, "http://localhost:0", KsqlRestConfig.ADVERTISED_LISTENER_CONFIG, "https://some.host:12345" ), new MetricCollecto...
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_density_xhdpi() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("xhdpi", config); assertThat(config.density).isEqualTo(DENSITY_XHIGH); }
@Override public Write.Append append(final Path file, final TransferStatus status) throws BackgroundException { final List<Path> segments; long size = 0L; try { segments = new SwiftObjectListService(session, regionService).list(new SwiftSegmentService(session, regionService) ...
@Test public void testAppendNoSegmentFound() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final SwiftRegionService regionService = new SwiftRegionService(session); ...
public void doMonitorWork() throws RemotingException, MQClientException, InterruptedException { long beginTime = System.currentTimeMillis(); this.monitorListener.beginRound(); TopicList topicList = defaultMQAdminExt.fetchAllTopicList(); for (String topic : topicList.getTopicList()) { ...
@Test public void testDoMonitorWork() throws RemotingException, MQClientException, InterruptedException { monitorService.doMonitorWork(); }