focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public KillApplicationResponse forceKillApplication( KillApplicationRequest request) throws YarnException, IOException { if (request == null || request.getApplicationId() == null) { routerMetrics.incrAppsFailedKilled(); String msg = "Missing forceKillApplication request or Application...
@Test public void testForceKillApplicationNotExists() throws Exception { LOG.info("Test FederationClientInterceptor: Force Kill Application - Not Exists"); ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1); KillApplicationRequest requestKill = KillApplicationR...
@Override public void invoke(final MainAction runnable) { this.invoke(runnable, false); }
@Test public void testInvoke() throws Exception { final CountDownLatch entry = new CountDownLatch(1); final AbstractController controller = new AbstractController() { @Override public void invoke(final MainAction runnable, final boolean wait) { assertFalse(wai...
public static boolean isValidLocalHost(String host) { return !isInvalidLocalHost(host); }
@Test void testIsValidLocalHost() { assertTrue(NetUtils.isValidLocalHost("1.2.3.4")); assertTrue(NetUtils.isValidLocalHost("128.0.0.1")); }
public static <T> List<T> batchTransform(final Class<T> clazz, List<?> srcList) { if (CollectionUtils.isEmpty(srcList)) { return Collections.emptyList(); } List<T> result = new ArrayList<>(srcList.size()); for (Object srcObject : srcList) { result.add(transform(clazz, srcObject)); } ...
@Test public void testBatchTransformSrcIsNull() { someList.add(null); assertNotNull(BeanUtils.batchTransform(String.class, someList)); }
@Override public byte[] toBitSet() { if (size == 0) { return Util.EMPTY_BYTE_ARRAY; } int offset = (size >>> 3); if ((size & 0xf) == 0) { byte[] array = new byte[offset]; Arrays.fill(array, (byte) 0xff); return array; } byte[] array = new byte[o...
@Test public void testToBitSet() { testToArray(13); testToArray(12); testToArray(0); testToArray(16); testToArray(43); testToArray(5); }
public static CoordinatorRecord newShareGroupEpochTombstoneRecord( String groupId ) { return new CoordinatorRecord( new ApiMessageAndVersion( new ShareGroupMetadataKey() .setGroupId(groupId), (short) 11 ), null /...
@Test public void testNewShareGroupEpochTombstoneRecord() { CoordinatorRecord expectedRecord = new CoordinatorRecord( new ApiMessageAndVersion( new ShareGroupMetadataKey() .setGroupId("group-id"), (short) 11), null); assert...
public static Map<String, AdvertisedListener> validateAndAnalysisAdvertisedListener(ServiceConfiguration config) { if (StringUtils.isBlank(config.getAdvertisedListeners())) { return Collections.emptyMap(); } Optional<String> firstListenerName = Optional.empty(); Map<String, L...
@Test(expectedExceptions = IllegalArgumentException.class) public void testMalformedListener() { ServiceConfiguration config = new ServiceConfiguration(); config.setAdvertisedListeners(":pulsar://127.0.0.1:6660"); MultipleListenerValidator.validateAndAnalysisAdvertisedListener(config); }
public static Manifest getManifest(Class<?> cls) throws IORuntimeException { URL url = ResourceUtil.getResource(null, cls); URLConnection connection; try { connection = url.openConnection(); }catch (final IOException e) { throw new IORuntimeException(e); } if (connection instanceof JarURLConnection) ...
@Test public void getManiFestTest(){ final Manifest manifest = ManifestUtil.getManifest(Test.class); assertNotNull(manifest); }
@Override public int hashCode() { return raw.hashCode(); }
@Test void two_different_tables_are_considered_non_equal() { assertNotEquals(createSimpleTable(), createSimpleNumberTable()); assertNotEquals(createSimpleTable().hashCode(), createSimpleNumberTable().hashCode()); }
public void subtractNutrients(Nutrients nutrients) { if(nutrients == null) return; subtractCalories(nutrients.getCalories()); subtractCarbohydrates(nutrients.getCarbohydrates()); subtractFats(nutrients.getFats()); subtractProteins(nutrients.getProteins()); }
@Test void subtractNegativeValues_shouldIncreaseValues() { modifyNutrients = new Nutrients( new Calories(new BigDecimal("-130")), new Carbohydrates(new BigDecimal("-5"), new BigDecimal("-2"), new BigDecimal("-3")), new Proteins(new BigDecimal("-5")), ...
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = RpcUtils.getMethodName(invocation); int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); final RpcStatus rpcStatus = R...
@Test void testInvokeRuntimeException() { Assertions.assertThrows(RuntimeException.class, () -> { URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0"); Invoker<ActiveLimitFilterTest> invoker = new RuntimeExceptionInvoker(url); Invo...
@Override public String eventName() { return "role"; }
@Test public void testEventName() { assertEquals("role", roleChangedEventTest.eventName()); }
public List<CloudtrailSNSNotification> parse(Message message) { LOG.debug("Parsing message."); try { LOG.debug("Reading message body {}.", message.getBody()); final SQSMessage envelope = objectMapper.readValue(message.getBody(), SQSMessage.class); if (envelope.messa...
@Test public void issue_44() throws Exception { // https://github.com/Graylog2/graylog-plugin-aws/issues/44 final Message message = new Message() .withBody("{\n" + " \"Type\" : \"Notification\",\n" + " \"MessageId\" : \"5b0a73e6-a4f8-...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMultimapEntriesCombineCacheAndWindmill() { final String tag = "multimap"; StateTag<MultimapState<byte[], Integer>> addr = StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of()); MultimapState<byte[], Integer> multimapState = underTest.state(NAMESPACE, addr); fina...
public void setSha1(String sha1) { this.sha1 = sha1; }
@Test @SuppressWarnings("squid:S2699") public void testSetSha1() { //already tested, this is just left so the IDE doesn't recreate it. }
@Override public void stop() { threadLocalSettings.unload(); }
@Test public void stop_calls_ThreadLocalSettings_remove() { underTest.stop(); verify(threadLocalSettings).unload(); verifyNoMoreInteractions(threadLocalSettings); }
@Override public ParSeqBasedCompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) { Task<?> that = getOrGenerateTaskFromStage(other); return nextStageByComposingTask(Task.par(_task, that).flatMap("thenAcceptBothAsync", (t, u) -> Task.blocking(() -> { ...
@Test public void testRunAfterBothAsync() throws Exception { CountDownLatch waitLatch = new CountDownLatch(1); CompletionStage<String> completionStage1 = createTestStage(TESTVALUE1); CompletionStage<String> completionStage2 = createTestStage(TESTVALUE2); finish(completionStage1.runAfterBothAsync(comple...
public static void initColumns(Table tbl, List<ImportColumnDesc> columnExprs, Map<String, Pair<String, List<String>>> columnToHadoopFunction) throws UserException { initColumns(tbl, columnExprs, columnToHadoopFunction, null, null, null, null, null, ...
@Test public void testSourceColumnCaseSensitive() throws UserException { // columns String c0Name = "c0"; columns.add(new Column(c0Name, Type.INT, true, null, true, null, "")); columnExprs.add(new ImportColumnDesc(c0Name, null)); String c1Name = "C1"; columns.add(new...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseIntervalUnit() { // Given: givenFunctions( function(EXPECTED, -1, INTERVALUNIT) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of( SqlIntervalUnit.INSTANCE))); // Then: assertThat(fun.name(), equa...
public static void mergeMap(boolean decrypt, Map<String, Object> config) { merge(decrypt, config); }
@Test public void testMap_mergeWhenFieldNotInValues_throwsException() { Map<String, Object> testMap = new HashMap<>(); testMap.put("key", "${TEST.somethingNotInValues}"); try { CentralizedManagement.mergeMap(true, testMap); fail(); } catch (ConfigException exp...
@SuppressWarnings("unchecked") @Override public boolean setFlushListener(final CacheFlushListener<K, V> listener, final boolean sendOldValues) { final KeyValueStore<Bytes, byte[]> wrapped = wrapped(); if (wrapped instanceof CachedStateStore) { retu...
@SuppressWarnings("unchecked") @Test public void shouldSetFlushListenerOnWrappedCachingStore() { setUpWithoutContext(); final CachedKeyValueStore cachedKeyValueStore = mock(CachedKeyValueStore.class); when(cachedKeyValueStore.setFlushListener(any(CacheFlushListener.class), eq(false))).t...
@Transactional public Release rollback(long releaseId, String operator) { Release release = findOne(releaseId); if (release == null) { throw NotFoundException.releaseNotFound(releaseId); } if (release.isAbandoned()) { throw new BadRequestException("release is not active"); } Strin...
@Test public void testRollback() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId, ...
public MethodBuilder onreturn(Object onreturn) { this.onreturn = onreturn; return getThis(); }
@Test void onreturn() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.onreturn("on-return-object"); Assertions.assertEquals("on-return-object", builder.build().getOnreturn()); }
public static ClassLoader findClassLoader(final ClassLoader proposed) { ClassLoader classLoader = proposed; if (classLoader == null) { classLoader = ReflectHelpers.class.getClassLoader(); } if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } return classLoa...
@Test public void testFindProperClassLoaderIfContextClassLoaderIsNull() throws InterruptedException { final ClassLoader[] classLoader = new ClassLoader[1]; Thread thread = new Thread(() -> classLoader[0] = ReflectHelpers.findClassLoader()); thread.setContextClassLoader(null); thread.start(); threa...
public boolean hasLogicTable(final String logicTable) { return shardingTables.containsKey(logicTable); }
@Test void assertNotHasLogicTable() { assertFalse(createBindingTableRule().hasLogicTable("New_Table")); }
public String findBaseType(String name) throws XPathExpressionException { return (String) xPath.compile( "/xs:schema/xs:complexType[@name='" + name + "']//xs:extension/@base") .evaluate(document, XPathConstants.STRING); }
@Test public void testFindBaseType() throws Exception { Document document = XmlHelper.buildNamespaceAwareDocument( ResourceUtils.getResourceAsFile("xmls/complex_type_w_parent.xml")); XPath xPath = XmlHelper.buildXPath(new CamelSpringNamespace()); domFinder = new DomFinder(doc...
public boolean isLastBlock(int blockNumber) { if (fileSize == 0) { return false; } throwIfInvalidBlockNumber(blockNumber); return blockNumber == (numBlocks - 1); }
@Test public void testArgChecks() throws Exception { // Should not throw. new BlockData(10, 5); new BlockData(5, 10); new BlockData(0, 10); // Verify it throws correctly. intercept(IllegalArgumentException.class, "'fileSize' must not be negative", () -> new BlockData(-1, 2)); i...
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { try { defaultMQAdminExt = createMQAdminExt(rpcHook); String brokerAddr = commandLine.getOptionValue('b').trim(); boolean isOrder = false; lo...
@Test public void testExecute() throws SubCommandException, IllegalAccessException, NoSuchFieldException { Field field = BrokerConsumeStatsSubCommad.class.getDeclaredField("defaultMQAdminExt"); field.setAccessible(true); field.set(cmd, defaultMQAdminExt); Options options = ServerUt...
Plugin create(Options.Plugin plugin) { try { return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument()); } catch (IOException | URISyntaxException e) { throw new CucumberException(e); } }
@Test void instantiates_rerun_plugin_with_file_arg() { PluginOption option = parse("rerun:" + tmp.resolve("rerun.txt")); plugin = fc.create(option); assertThat(plugin.getClass(), is(equalTo(RerunFormatter.class))); }
public Schema mergeTables( Map<FeatureOption, MergingStrategy> mergingStrategies, Schema sourceSchema, List<SqlNode> derivedColumns, List<SqlWatermark> derivedWatermarkSpecs, SqlTableConstraint derivedPrimaryKey) { SchemaBuilder schemaBuilder = ...
@Test void mergeExcludingConstraintsOnDuplicate() { Schema sourceSchema = Schema.newBuilder() .column("one", DataTypes.INT().notNull()) .column("two", DataTypes.STRING().notNull()) .column("three", DataTypes.FLOAT()) ...
@Override public SecurityLevel getSecurityLevel() { return this.securityLevel; }
@Test public void testGetSecurityLevel() { assertEquals(SecurityLevel.AUTH_PRIV, v3SnmpConfiguration.getSecurityLevel().getSnmpValue()); }
@Override public ObjectNode encode(RoleInfo roleInfo, CodecContext context) { checkNotNull(roleInfo, "RoleInfo cannot be null"); ObjectNode result = context.mapper().createObjectNode(); if (roleInfo.master() != null) { result.put(MASTER, roleInfo.master().id()); } ...
@Test public void testRoleInfoEncode() { NodeId masterNodeId = NodeId.nodeId("1"); NodeId backupNodeId1 = NodeId.nodeId("1"); NodeId backupNodeId2 = NodeId.nodeId("2"); NodeId backupNodeId3 = NodeId.nodeId("3"); List<NodeId> backupNodeIds = ImmutableList.of(ba...
public List<Chapter> getChapters() { return chapters; }
@Test public void testRealFileHindenburgJournalistPro() throws IOException, ID3ReaderException { CountingInputStream inputStream = new CountingInputStream(getClass().getClassLoader() .getResource("hindenburg-journalist-pro.mp3").openStream()); ChapterReader reader = new ChapterReader...
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@Test public void testPartitionedBucketLong() throws Exception { createPartitionedTable(spark, tableName, "bucket(5, id)"); SparkScanBuilder builder = scanBuilder(); BucketFunction.BucketLong function = new BucketFunction.BucketLong(DataTypes.LongType); UserDefinedScalarFunc udf = toUDF(function, ex...
public static List<UpdateRequirement> forReplaceView( ViewMetadata base, List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != base, "Invalid view metadata: null"); Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Build...
@Test public void addSchemaForView() { int lastColumnId = 1; List<UpdateRequirement> requirements = UpdateRequirements.forReplaceView( viewMetadata, ImmutableList.of( new MetadataUpdate.AddSchema(new Schema(), lastColumnId), new MetadataUpdate.Ad...
@Override public ConfiguredDataSourceProvenance getProvenance() { return provenance; }
@Test public void testBasic() { CSVDataSource<MockOutput> dataSource = new CSVDataSource<>(dataFile, rowProcessor, true); MutableDataset<MockOutput> dataset = new MutableDataset<>(dataSource); assertEquals(6,dataset.size(),"Found an incorrect number of rows when loading the csv."); ...
public final void addStateStore(final StoreBuilder<?> storeBuilder, final String... processorNames) { addStateStore(new StoreBuilderWrapper(storeBuilder), false, processorNames); }
@Test public void shouldNotAddNullStateStoreSupplier() { assertThrows(NullPointerException.class, () -> builder.addStateStore((StoreBuilder<?>) null)); }
public static String format( String xml ) { XMLStreamReader rd = null; XMLStreamWriter wr = null; StringWriter result = new StringWriter(); try { rd = INPUT_FACTORY.createXMLStreamReader( new StringReader( xml ) ); synchronized ( OUTPUT_FACTORY ) { // BACKLOG-18743: This object was...
@Test public void test2() throws Exception { String inXml, expectedXml; try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterIn2.xml" ) ) { inXml = IOUtils.toString( in ); } try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterExpected2.xml" ...
@Override public boolean isDone() { if (delegate.isDone()) { try { ensureResultSet(Long.MAX_VALUE, TimeUnit.DAYS); } catch (ExecutionException | CancellationException | TimeoutException ignored) { ignore(ignored); } return true;...
@Test public void completeDelegate_withException_callbackBeforeGet_invokeIsDoneOnOuter_callbacksRun() { BiConsumer<String, Throwable> callback = getStringExecutionCallback(); delegateThrowException = true; delegateFuture.run(); outerFuture.whenCompleteAsync(callback, CALLER_RUNS); ...
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { Job job = ValueAggregatorJob.createValueAggregatorJob(args , new Class[] {WordCountPlugInClass.class}); job.setJarByClass(AggregateWordCount.class); int re...
@Test void testAggregateTestCount() throws IOException, ClassNotFoundException, InterruptedException { ExitUtil.disableSystemExit(); FileSystem fs = getFileSystem(); fs.mkdirs(INPUT_PATH); Path file1 = new Path(INPUT_PATH, "file1"); Path file2 = new Path(INPUT_PATH, "file2"); FileUtil.w...
@VisibleForTesting synchronized List<RemoteNode> getLeastLoadedNodes() { long currTime = System.currentTimeMillis(); if ((currTime - lastCacheUpdateTime > cacheRefreshInterval) || (cachedNodes == null)) { cachedNodes = convertToRemoteNodes( this.nodeMonitor.selectLeastLoadedNodes(this....
@Test(timeout = 600000) public void testContainerPromoteAndDemoteBeforeContainerStart() throws Exception { HashMap<NodeId, MockNM> nodes = new HashMap<>(); MockNM nm1 = new MockNM("h1:1234", 4096, rm.getResourceTrackerService()); nodes.put(nm1.getNodeId(), nm1); MockNM nm2 = new MockNM("h1:4321", 4096...
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void outer_lock_simpleName() { assertThat( bind( "Test", "lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", ...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseWindows10WithEdgeTest() { final String uaStr = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"; final UserAgent ua = UserAgentUtil.parse(uaStr); assertEquals("MSEdge", ua.getBrowser().toString()); assertE...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); gauges.put("total.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit()); gauges.put("total.used", (Gauge<Long>) () -...
@Test public void hasAGaugeForHeapUsed() { final Gauge gauge = (Gauge) gauges.getMetrics().get("heap.used"); assertThat(gauge.getValue()) .isEqualTo(30L); }
private static int countJoinNode(OptExpression root, boolean[] hasOuterOrSemi) { int count = 0; Operator operator = root.getOp(); for (OptExpression child : root.getInputs()) { if (operator instanceof LogicalJoinOperator && ((LogicalJoinOperator) operator).getJoinHint().isEmpty()) { ...
@Test public void testCountJoinNode() { OptExpression root = OptExpression.create( new LogicalJoinOperator(JoinOperator.LEFT_OUTER_JOIN, null), OptExpression.create(new LogicalJoinOperator(JoinOperator.LEFT_OUTER_JOIN, null), OptExpression.create(new L...
public int getPathLength() { return beginPath.length + endPath.length; }
@Test public void oneLevelAncestorPathLength(){ final NodeModel parent = root(); final NodeModel node1 = new NodeModel("node1", map); parent.insert(node1); final NodeModel node2 = new NodeModel("node2", map); parent.insert(node2); final NodeRelativePath nodeRelativePath = new NodeRelativePath(node1, node2)...
@Override public int getLineHashesVersion(Component component) { if (significantCodeRepository.getRangesPerLine(component).isPresent()) { return LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue(); } else { return LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue(); } }
@Test public void should_return_version_of_line_hashes_without_significant_code_in_the_report() { when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty()); assertThat(underTest.getLineHashesVersion(file)).isEqualTo(LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue()); verify(...
@Override public String generate() { return UUID.randomUUID().toString(); }
@Test public void generate_shouldGenerateUniqueIds() { String requestId1 = requestIdGenerator.generate(); String requestId2 = requestIdGenerator.generate(); String requestId3 = requestIdGenerator.generate(); assertThat(requestId1).isNotEqualTo(requestId2).isNotEqualTo(requestId3); }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void threads_default_1() { RuntimeOptions options = parser .parse() .build(); assertThat(options.getThreads(), is(1)); }
@Override public double p(int k) { if (k == 0) { return q; } else if (k == 1) { return p; } else { return 0.0; } }
@Test public void testP() { System.out.println("p"); BernoulliDistribution instance = new BernoulliDistribution(0.3); instance.rand(); assertEquals(0.7, instance.p(0), 1E-7); assertEquals(0.3, instance.p(1), 1E-7); assertEquals(0.0, instance.p(2), 1E-7); }
protected void updateCurrentDir() { String prevCurrentDir = variables.getVariable( Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY ); String currentDir = variables.getVariable( repository != null ? Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY : filename != null ? Const....
@Test public void testUpdateCurrentDirWithRepository( ) { JobMeta jobMetaTest = new JobMeta( ); RepositoryDirectoryInterface path = mock( RepositoryDirectoryInterface.class ); when( path.getPath() ).thenReturn( "aPath" ); jobMetaTest.setRepository( mock( Repository.class ) ); jobMetaTest.setRepo...
@SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/21068) }) /* * Returns an iterables containing all distinct keys in this multimap. */ public PrefetchableIterable<K> keys() { checkState( !isClosed, "Multimap user state is no longer usable because it is clo...
@Test public void testNoPersistedValues() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient(Collections.emptyMap()); MultimapUserState<byte[], String> userState = new MultimapUserState<>( Caches.noop(), fakeClient, "instructionId", ...
@Override protected void runPendingJob() throws AlterCancelException { Preconditions.checkState(jobState == JobState.PENDING, jobState); LOG.info("begin to send create temp partitions. job: {}", jobId); Database db = GlobalStateMgr.getCurrentState().getDb(dbId); if (db == null) { ...
@Test public void testSchemaChangeWhileTabletNotStable() throws Exception { SchemaChangeHandler schemaChangeHandler = GlobalStateMgr.getCurrentState().getSchemaChangeHandler(); Database db = GlobalStateMgr.getCurrentState().getDb(GlobalStateMgrTestUtil.testDb1); OlapTable olapTable = (OlapTa...
public int validate( final ServiceContext serviceContext, final List<ParsedStatement> statements, final SessionProperties sessionProperties, final String sql ) { requireSandbox(serviceContext); final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext)); ...
@Test public void shouldThrowExceptionIfValidationFails() { // Given: givenRequestValidator( ImmutableMap.of(CreateStream.class, statementValidator) ); doThrow(new KsqlException("Fail")) .when(statementValidator).validate(any(), any(), any(), any()); final List<ParsedStatement> st...
public List<String> get(Component component) { Preconditions.checkState(contains(component), "Source line hashes for component %s not cached", component); return load(getId(component)); }
@Test public void get_throws_ISE_if_not_cached() { Component component = createComponent(1); assertThatThrownBy(() -> underTest.get(component)) .isInstanceOf(IllegalStateException.class) .hasMessage("Source line hashes for component ReportComponent{ref=1, key='FILE_KEY', type=FILE} not cached"); ...
public Node getCurrent() { return current; }
@Test public void getCurrentNoPushReturnsRoot() { assertThat(hierarchy.getCurrent().isRootNode(), is(true)); }
@Override public Integer addScoreAndGetRank(V object, Number value) { return get(addScoreAndGetRankAsync(object, value)); }
@Test public void testAddScoreAndGetRank() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple"); Integer res1 = set.addScoreAndGetRank("12", 12); assertThat(res1).isEqualTo(0); Integer res2 = set.addScoreAndGetRank("15", 10); assertThat(res2).isEqualTo(0); ...
public static <T> CheckedFunction0<T> recover(CheckedFunction0<T> function, CheckedFunction1<Throwable, T> exceptionHandler) { return () -> { try { return function.apply(); } catch (Throwable throwable) { return exceptionHandler.apply(throwable); ...
@Test public void shouldRecoverFromException() throws Throwable { CheckedFunction0<String> callable = () -> { throw new IOException("BAM!"); }; CheckedFunction0<String> callableWithRecovery = VavrCheckedFunctionUtils.recover(callable, (ex) -> "Bla"); String result = call...
@Override public V get(final K key) { Objects.requireNonNull(key); final List<ReadOnlyKeyValueStore<K, V>> stores = storeProvider.stores(storeName, storeType); for (final ReadOnlyKeyValueStore<K, V> store : stores) { try { final V result = store.get(key); ...
@Test public void shouldThrowNullPointerExceptionOnGetNullKey() { assertThrows(NullPointerException.class, () -> theStore.get(null)); }
Future<RecordMetadata> send(final ProducerRecord<byte[], byte[]> record, final Callback callback) { maybeBeginTransaction(); try { return producer.send(record, callback); } catch (final KafkaException uncaughtException) { if (isRecoverable(...
@Test public void shouldThrowTaskMigrateExceptionOnEosBeginTxnError() { eosAlphaMockProducer.beginTransactionException = new KafkaException("KABOOM!"); // calling `send()` implicitly starts a new transaction final StreamsException thrown = assertThrows( StreamsException.class, ...
@Private @VisibleForTesting static void checkResourceRequestAgainstAvailableResource(Resource reqResource, Resource availableResource) throws InvalidResourceRequestException { for (int i = 0; i < ResourceUtils.getNumberOfCountableResourceTypes(); i++) { final ResourceInformation requestedRI = ...
@Test public void testCustomResourceRequestedUnitIsGreaterThanAvailableUnit2() { Resource requestedResource = ResourceTypesTestHelper.newResource(1, 1, ImmutableMap.<String, String>builder().put("custom-resource-1", "11M") .build()); Resource availableResource = Re...
@Override public String getLongFormat(final long milliseconds, boolean natural) { synchronized(longDateFormatter) { if(-1 == milliseconds) { return LocaleFactory.localizedString("Unknown"); } longDateFormatter.setTimeZone(NSTimeZone.timeZoneWithName(timezo...
@Test public void testGetLongFormat() { final UserDateFormatter f = new UserDefaultsDateFormatter(TimeZone.getDefault().getID()); assertNotNull(f.getLongFormat(System.currentTimeMillis(), false)); assertNotNull(f.getLongFormat(System.currentTimeMillis(), true)); }
@Override public ExecuteContext before(ExecuteContext context) { Object object = context.getObject(); if (object instanceof BaseLoadBalancer) { List<Object> serverList = getServerList(context.getMethod().getName(), object); if (CollectionUtils.isEmpty(serverList)) { ...
@Test public void testBeforeWithThreadLocal() { ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", "")); interceptor.before(context); BaseLoadBalancer loadBalancer = (BaseLoadBalancer) context.getObject(); List<Server> servers = loadBalancer.getAllServers(); ...
@Override public DataNodeDto removeNode(String nodeId) throws NodeNotFoundException { final DataNodeDto node = nodeService.byNodeId(nodeId); if (node.getDataNodeStatus() != DataNodeStatus.AVAILABLE) { throw new IllegalArgumentException("Only running data nodes can be removed from the clu...
@Test public void removeNodeFailsForLastNode() throws NodeNotFoundException { final String testNodeId = "node"; nodeService.registerServer(buildTestNode(testNodeId, DataNodeStatus.AVAILABLE)); Exception e = assertThrows(IllegalArgumentException.class, () -> { classUnderTest.remo...
public static long write(InputStream is, OutputStream os) throws IOException { return write(is, os, BUFFER_SIZE); }
@Test void testWrite5() throws Exception { assertThat((int) IOUtils.write(reader, writer), equalTo(TEXT.length())); }
public void addConfigListenContext(String group, String dataId, String tenant, String md5) { ConfigListenContext configListenContext = new ConfigListenContext(); configListenContext.dataId = dataId; configListenContext.group = group; configListenContext.md5 = md5; configListenCon...
@Override @Test public void testSerialize() throws JsonProcessingException { ConfigBatchListenRequest configBatchListenRequest = new ConfigBatchListenRequest(); configBatchListenRequest.putAllHeader(HEADERS); configBatchListenRequest.addConfigListenContext(GROUP, DATA_ID, TENANT, MD5); ...
JavaClasses getClassesToAnalyzeFor(Class<?> testClass, ClassAnalysisRequest classAnalysisRequest) { checkNotNull(testClass); checkNotNull(classAnalysisRequest); if (cachedByTest.containsKey(testClass)) { return cachedByTest.get(testClass); } LocationsKey locations =...
@Test public void filters_jars_relative_to_class() { JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class, analyzePackagesOf(Rule.class)); assertThat(classes).isNotEmpty(); for (JavaClass clazz : classes) { assertThat(clazz.getPackageName()).doesNotContain("tngtech...
public static String generateDatabaseId(String baseString) { checkArgument(baseString.length() != 0, "baseString cannot be empty!"); String databaseId = generateResourceId( baseString, ILLEGAL_DATABASE_CHARS, REPLACE_DATABASE_CHAR, MAX_DATABASE_ID_LENGTH,...
@Test public void testGenerateDatabaseIdShouldThrowErrorWithEmptyInput() { String testBaseString = ""; assertThrows(IllegalArgumentException.class, () -> generateDatabaseId(testBaseString)); }
public static int compare(String unitA, long valueA, String unitB, long valueB) { checkUnitArgument(unitA); checkUnitArgument(unitB); if (unitA.equals(unitB)) { return Long.compare(valueA, valueB); } Converter unitAC = getConverter(unitA); Converter unitBC = getConverter(unitB); ...
@Test void testCompare() { String unitA = "P"; long valueA = 1; String unitB = "p"; long valueB = 2; assertEquals(1, UnitsConversionUtil.compare(unitA, valueA, unitB, valueB)); assertEquals(-1, UnitsConversionUtil.compare(unitB, valueB, unitA, valueA)); assertEquals(0, ...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { if(file.isDirectory()) { return this.toAttributes(new FoldersApi(new BoxApiClient(session.getClient())).getFoldersId(fileid.getFileId(file), ...
@Test public void testFindRoot() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final BoxAttributesFinderFeature f = new BoxAttributesFinderFeature(session, fileid); final PathAttributes attributes = f.find(new Path("/", EnumSet.of(Path.Type.volume, Path....
@Override public void mutate() { for (int i = 0; i < bits.length; i++) { if (MathEx.random() < mutationRate) { bits[i] ^= 1; } } }
@Test public void testMutate() { System.out.println("mutate"); MathEx.setSeed(19650218); // to get repeatable results. byte[] father = {1,1,1,0,1,0,0,1,0,0,0}; BitString instance = new BitString(father.clone(), null, Crossover.SINGLE_POINT, 1.0, 0.1); instance.mutate(); ...
public boolean remove(long key1, long key2) { checkBiggerEqualZero(key1); long h = hash(key1, key2); return getSection(h).remove(key1, key2, ValueNotFound, ValueNotFound, (int) h); }
@Test public void testRemove() { ConcurrentLongLongPairHashMap map = ConcurrentLongLongPairHashMap .newBuilder() .build(); assertTrue(map.isEmpty()); assertTrue(map.put(1, 1, 11, 11)); assertFalse(map.isEmpty()); assertFalse(map.remove(0, 0))...
@Override public void define(Context context) { NewController features = context.createController("api/features") .setDescription("Provides information about features available in SonarQube") .setSince("9.6"); list.define(features); features.done(); }
@Test public void define_shouldHasAtLeastOneAction() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller(CONTROLLER_FEATURES); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty...
public Properties getProperties() { return properties; }
@Test public void testUriWithHttpProtocols() throws SQLException { String protocols = "h2,http/1.1"; PrestoDriverUri parameters = createDriverUri("presto://localhost:8080?protocols=" + protocols); Properties properties = parameters.getProperties(); assertEquals(proper...
public OffsetAndMetadata findNextCommitOffset(final String commitMetadata) { boolean found = false; long currOffset; long nextCommitOffset = committedOffset; for (KafkaSpoutMessageId currAckedMsg : ackedMsgs) { // complexity is that of a linear scan on a TreeMap currOffset ...
@Test public void testFindNextOffsetWithAckedButNotEmittedOffsetGap() { /** * If topic compaction is enabled in Kafka some offsets may be deleted. * We distinguish this case from regular gaps in the acked offset sequence caused by out of order acking * by checking that offsets in ...
@Override public Material toOldMaterial(String name, String folder, String password) { GitMaterial git = new GitMaterial(url, branch, folder); setName(name, git); git.setUserName(username); git.setPassword(password); git.setSubmoduleFolder(submoduleFolder); git.setId(...
@Test void shouldCreateMaterialFromMaterialInstance() { final GitMaterialInstance materialInstance = new GitMaterialInstance("https://example.com", "bob", "feature", "submodule_folder", "some-flyweight"); materialInstance.setId(100L); final GitMaterial material = (GitMateria...
public BooleanPredicate setValue(boolean value) { this.value = value; return this; }
@Test void requireThatEqualsIsImplemented() { BooleanPredicate lhs = new BooleanPredicate(true); assertEquals(lhs, lhs); assertNotEquals(lhs, new Object()); BooleanPredicate rhs = new BooleanPredicate(false); assertNotEquals(lhs, rhs); rhs.setValue(true); ass...
@Override public boolean add(E element) { return add(element, element.hashCode()); }
@Test(expected = NullPointerException.class) public void testAddAllThrowsOnNullElement() { final OAHashSet<Integer> set = new OAHashSet<>(8); final Collection<Integer> elementsToAdd = new ArrayList<>(2); elementsToAdd.add(1); elementsToAdd.add(null); set.addAll(elementsToAd...
public static MethodHandle findMethod(Class<?> callerClass, String name, MethodType type) { if (StrUtil.isBlank(name)) { return findConstructor(callerClass, type); } MethodHandle handle = null; final MethodHandles.Lookup lookup = lookup(callerClass); try { handle = lookup.findVirtual(callerClass, name,...
@Test public void findMethodTest() throws Throwable { MethodHandle handle = MethodHandleUtil.findMethod(Duck.class, "quack", MethodType.methodType(String.class)); assertNotNull(handle); // 对象方法自行需要绑定对象或者传入对象参数 String invoke = (String) handle.invoke(new BigDuck()); assertEquals("Quack", invoke); // 对象的...
@Override public FileType getType() throws FileSystemException { return resolvedFileObject.getType(); }
@Test public void testDelegatesGetType() throws FileSystemException { when( resolvedFileObject.getType() ).thenReturn( FileType.FILE ); assertEquals( FileType.FILE, fileObject.getType() ); when( resolvedFileObject.getType() ).thenReturn( FileType.FOLDER ); assertEquals( FileType.FOLDER, fileObject....
public static String findAddress(List<NodeAddress> addresses, NodeAddressType preferredAddressType) { if (addresses == null) { return null; } Map<String, String> addressMap = addresses.stream() .collect(Collectors.toMap(NodeAddress::getType, NodeAddress::getAddres...
@Test public void testFindAddressNotFound() { List<NodeAddress> addresses = new ArrayList<>(3); addresses.add(new NodeAddressBuilder().withType("SomeAddress").withAddress("my.external.address").build()); addresses.add(new NodeAddressBuilder().withType("SomeOtherAddress").withAddress("my.in...
public void startAsync() { try { udfLoader.load(); ProcessingLogServerUtils.maybeCreateProcessingLogTopic( serviceContext.getTopicClient(), processingLogConfig, ksqlConfig); if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) { log.warn...
@Test public void shouldRunCtasStatements() { // Given: final PreparedStatement<?> ctas = PreparedStatement.of("CTAS", new CreateTableAsSelect(SOME_NAME, query, false, false, CreateSourceAsProperties.none())); final ConfiguredStatement<?> configured = ConfiguredStatement .of(ctas, SessionC...
public boolean isMatch(Resource resource) { if (this.resourceType == ResourceType.ANY) { return true; } if (this.resourceType != resource.resourceType) { return false; } switch (resourcePattern) { case ANY: return true; ...
@Test public void isMatch() { }
@Override public PageResult<PostDO> getPostPage(PostPageReqVO reqVO) { return postMapper.selectPage(reqVO); }
@Test public void testGetPostPage() { // mock 数据 PostDO postDO = randomPojo(PostDO.class, o -> { o.setName("码仔"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); postMapper.insert(postDO); // 测试 name 不匹配 postMapper.insert(cloneIgnoreId(po...
boolean shouldSetAvailableForAnotherInput() { return (selectedInputsMask & allSelectedMask & ~availableInputsMask) != 0; }
@Test void testShouldSetAvailableForAnotherInput() { InputSelection secondAndThird = new InputSelection.Builder().select(2).select(3).build(); MultipleInputSelectionHandler selectionHandler = new MultipleInputSelectionHandler(() -> secondAndThird, 3); selectionHandler.nextSe...
public Object getField(Object record, String name, int position) { return ((IndexedRecord) record).get(position); }
@Test void getEmptySchemaField() throws Exception { assertThrows(AvroRuntimeException.class, () -> { Schema s = Schema.createRecord("schemaName", "schemaDoc", "namespace", false); s.getField("foo"); }); }
public static Status unblock( final UnsafeBuffer logMetaDataBuffer, final UnsafeBuffer termBuffer, final int blockedOffset, final int tailOffset, final int termId) { Status status = NO_ACTION; int frameLength = frameLengthVolatile(termBuffer, blockedOffset); ...
@Test void shouldPatchNonCommittedMessage() { final int termOffset = 0; final int messageLength = HEADER_LENGTH * 4; final int tailOffset = messageLength; when(mockTermBuffer.getIntVolatile(termOffset)).thenReturn(-messageLength); assertEquals( UNBLOCKED, Te...
@Override public <PS extends Serializer<P>, P> KeyValueIterator<K, V> prefixScan(final P prefix, final PS prefixKeySerializer) { Objects.requireNonNull(prefix); Objects.requireNonNull(prefixKeySerializer); final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = n...
@Test public void shouldThrowNullPointerExceptionOnPrefixScanNullPrefix() { assertThrows(NullPointerException.class, () -> theStore.prefixScan(null, new StringSerializer())); }
@LiteralParameters("x") @ScalarOperator(GREATER_THAN_OR_EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean greaterThanOrEqual(@SqlType("char(x)") Slice left, @SqlType("char(x)") Slice right) { return compareChars(left, right) >= 0; }
@Test public void testGreaterThanOrEqual() { assertFunction("cast('bar' as char(5)) >= cast('foo' as char(3))", BOOLEAN, false); assertFunction("cast('foo' as char(5)) >= cast('bar' as char(3))", BOOLEAN, true); assertFunction("cast('bar' as char(3)) >= cast('foo' as char(5))", BOOLEAN, ...
public int triggerBlockReport(String[] argv) throws IOException { List<String> args = new LinkedList<String>(); for (int j = 1; j < argv.length; j++) { args.add(argv[j]); } // Block report to a specific namenode InetSocketAddress namenodeAddr = null; String nnHostPort = StringUtils.popOpti...
@Test(timeout = 30000) public void testTriggerBlockReport() throws Exception { redirectStream(); final DFSAdmin dfsAdmin = new DFSAdmin(conf); final DataNode dn = cluster.getDataNodes().get(0); final NameNode nn = cluster.getNameNode(); final String dnAddr = String.format( "%s:%d", ...
static Builder builder() { return new AutoValue_CsvIOParseError.Builder(); }
@Test public void usableInSingleOutput() { List<CsvIOParseError> want = Arrays.asList( CsvIOParseError.builder() .setMessage("error message") .setObservedTimestamp(Instant.now()) .setStackTrace("stack trace") .build(), ...
public void createNewCodeDefinition(DbSession dbSession, String projectUuid, String mainBranchUuid, String defaultBranchName, String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) { boolean isCommunityEdition = editionProvider.get().filter(EditionProvider.Edition.COMMUNITY::equals).isPresent()...
@Test public void createNewCodeDefinition_return_days_value_for_number_of_days_type() { String numberOfDays = "30"; newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH_UUID, MAIN_BRANCH, NUMBER_OF_DAYS.name(), numberOfDays); Optional<NewCodePeriodDto> newCodePeri...
public synchronized void lockLeakCheck() { if (!openLockTrace) { LOG.warn("not open lock leak check func"); return; } if (threadCountMap.isEmpty()) { LOG.warn("all lock has release"); return; } setLastException(new Exception("lock Leak")); threadCountMap.forEach((name, tr...
@Test(timeout = 5000) public void testLockLeakCheck() { manager.writeLock(LockLevel.BLOCK_POOl, "test"); manager.lockLeakCheck(); Exception lastException = manager.getLastException(); assertEquals(lastException.getMessage(), "lock Leak"); }
@SuppressWarnings({"CyclomaticComplexity"}) @Override public void process(ApplicationEvent event) { switch (event.type()) { case COMMIT_ASYNC: process((AsyncCommitEvent) event); return; case COMMIT_SYNC: process((SyncCommitEvent) e...
@Test public void testPrepClosingCommitEvents() { setupProcessor(true); List<NetworkClientDelegate.UnsentRequest> results = mockCommitResults(); doReturn(new NetworkClientDelegate.PollResult(100, results)).when(commitRequestManager).pollOnClose(); processor.process(new CommitOnCloseE...
@Override public ByteBufFormat byteBufFormat() { if (byteBufFormat == SIMPLE) { return ByteBufFormat.SIMPLE; } else if (byteBufFormat == HEX_DUMP) { return ByteBufFormat.HEX_DUMP; } throw new UnsupportedOperationException("ReactorNettyLoggingHandler isn't using the classic ByteBufFormat."); }
@Test void shouldThrowUnsupportedOperationExceptionWhenByteBufFormatIsCalled() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> defaultCharsetReactorNettyLoggingHandler.byteBufFormat()); }
@Override protected SchemaTransform from(SchemaTransformConfiguration configuration) { return new IcebergWriteSchemaTransform(configuration); }
@Test public void testBuildTransformWithRow() { Map<String, String> properties = new HashMap<>(); properties.put("type", CatalogUtil.ICEBERG_CATALOG_TYPE_HADOOP); properties.put("warehouse", "test_location"); Row transformConfigRow = Row.withSchema(new IcebergWriteSchemaTransformProvider().co...
void loadState(final long nextServiceSessionId, final long logServiceSessionId, final int pendingMessageCapacity) { this.nextServiceSessionId = nextServiceSessionId; this.logServiceSessionId = logServiceSessionId; pendingMessages.reset(pendingMessageCapacity); }
@Test void loadInvalid() { final CountersManager countersManager = Tests.newCountersManager(16 * 1024); final int counterId = countersManager.allocate("test"); final Counter counter = new Counter(countersManager, 0, counterId); final LogPublisher logPublisher = mock(LogPublisher....
public void commit() throws SQLException { Collection<SQLException> exceptions = new LinkedList<>(); if (databaseConnectionManager.getConnectionSession().getConnectionContext().getTransactionContext().isExceptionOccur()) { exceptions.addAll(rollbackConnections()); } else { ...
@Test void assertCommit() throws SQLException { localTransactionManager.commit(); verify(connectionContext.getTransactionContext()).isExceptionOccur(); verify(connection).commit(); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final RemoteFile handle = session.sftp().open(file.getAbsolute(), EnumSet.of(OpenMode.READ)); final int maxUnconfirmedReads = this.get...
@Test public void testReadRange() throws Exception { final Path home = new SFTPHomeDirectoryService(session).find(); final Path test = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new SFTPTouchFeature(session).touch(test, new TransferStatus()); final int ...
public List<R> scanForResourcesInClasspathRoot(URI root, Predicate<String> packageFilter) { requireNonNull(root, "root must not be null"); requireNonNull(packageFilter, "packageFilter must not be null"); BiFunction<Path, Path, Resource> createResource = createClasspathRootResource(); ret...
@Test void scanForResourcesInClasspathRoot() { URI classpathRoot = new File("src/test/resources/io/cucumber/core/resource/test").toURI(); List<URI> resources = resourceScanner.scanForResourcesInClasspathRoot(classpathRoot, aPackage -> true); assertThat(resources, containsInAnyOrder( ...