focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public TDescribeTableResult describeTable(TDescribeTableParams params) throws TException { LOG.debug("get desc table request: {}", params); TDescribeTableResult result = new TDescribeTableResult(); List<TColumnDef> columns = Lists.newArrayList(); result.setColumns(columns);...
@Test public void testDefaultValueMeta() throws Exception { starRocksAssert.withDatabase("test_table").useDatabase("test_table") .withTable("CREATE TABLE `test_default_value` (\n" + " `id` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT \"\",\n" + ...
@Override public synchronized void cleanupAll() { try { if (usingStaticInstance) { if (databaseAdminClient != null) { Failsafe.with(retryOnQuotaException()) .run(() -> databaseAdminClient.dropDatabase(instanceId, databaseId)); } } else { LOG.info("Delet...
@Test public void testCleanupAllShouldNotDeleteInstanceWhenStatic() { // arrange doNothing().when(databaseAdminClient).dropDatabase(any(), any()); when(spanner.getInstanceAdminClient()).thenReturn(instanceAdminClient); when(spanner.getDatabaseAdminClient()).thenReturn(databaseAdminClient); testMan...
public static Set<String> findKeywordsFromCrashReport(String crashReport) { Matcher matcher = CRASH_REPORT_STACK_TRACE_PATTERN.matcher(crashReport); Set<String> result = new HashSet<>(); if (matcher.find()) { for (String line : matcher.group("stacktrace").split("\\n")) { ...
@Test public void wizardry() throws IOException { assertEquals( new HashSet<>(Arrays.asList("wizardry", "electroblob", "projectile")), CrashReportAnalyzer.findKeywordsFromCrashReport(loadLog("/crash-report/mod/wizardry.txt"))); }
public Mono<Table<String, TopicPartition, Long>> listConsumerGroupOffsets(List<String> consumerGroups, // all partitions if null passed @Nullable List<TopicPartition> p...
@Test void testListConsumerGroupOffsets() throws Exception { String topic = UUID.randomUUID().toString(); String anotherTopic = UUID.randomUUID().toString(); createTopics(new NewTopic(topic, 2, (short) 1), new NewTopic(anotherTopic, 1, (short) 1)); fillTopic(topic, 10); Function<String, KafkaCons...
@Override public void update(Object elem) throws Exception { // Increment object counter. if (objectCount != null) { objectCount.addValue(1L); } // Increment byte counter. if ((byteCountObserver != null || meanByteCountObserver != null) && (sampleElement() || elementByteSizeObservab...
@Test public void testNullArgument() throws Exception { TestOutputCounter outputCounter = new TestOutputCounter(NameContextsForTests.nameContextForTest()); thrown.expect(CoderException.class); outputCounter.update(null); }
private static BinaryArray fromPrimitiveArray(Object arr, int offset, int length, Field field) { BinaryArray result = new BinaryArray(field); final long headerInBytes = calculateHeaderInBytes(length); final long valueRegionInBytes = result.elementSize * length; final long totalSize = headerInBytes + val...
@Test(enabled = false) public void testAccessPerf() { int length = 10000; int[] arr = new int[length]; Random random = new Random(); for (int i = 0; i < length; i++) { arr[i] = random.nextInt(); } BinaryArray binaryArray = BinaryArray.fromPrimitiveArray(arr); int iterNums = 100_000; ...
public LegacyDeleteResult<T, K> remove(DBObject query) { return new LegacyDeleteResult<>(delegate.deleteMany(new BasicDBObject(query.toMap()))); }
@Test void remove() { final var collection = jacksonCollection("simple", Simple.class); final var foo = new Simple("000000000000000000000001", "foo"); final var bar = new Simple("000000000000000000000002", "bar"); collection.insert(List.of(foo, bar)); assertThat(collection.r...
@Nonnull public static <T> StreamSource<T> connect(@Nonnull Properties properties, @Nonnull FunctionEx<SourceRecord, T> projectionFn) { return connect(properties, projectionFn, DEFAULT_RECONNECT_BEHAVIOR); }
@Test public void should_fail_when_no_name_property() { Properties properties = new Properties(); assertThatThrownBy(() -> connect(properties, TestUtil::convertToString)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property 'name' is required"); }
@VisibleForTesting List<BatchInterface> makeGetBatches( Collection<GcsPath> paths, List<StorageObjectOrIOException[]> results) throws IOException { List<BatchInterface> batches = new ArrayList<>(); for (List<GcsPath> filesToGet : Lists.partition(Lists.newArrayList(paths), MAX_REQUESTS_PER_BATCH)...
@Test public void testMakeGetBatches() throws IOException { GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil(); // Small number of files fits in 1 batch List<StorageObjectOrIOException[]> results = Lists.newArrayList(); List<BatchInterface> batches = gcsUtil.makeGetBatches(makeGcsPaths("s"...
@Override public boolean canPass(Node node, int acquireCount) { return canPass(node, acquireCount, false); }
@Test public void testWarmUp() throws InterruptedException { try (MockedStatic<TimeUtil> mocked = super.mockTimeUtil()) { WarmUpController warmupController = new WarmUpController(10, 10, 3); setCurrentMillis(mocked, System.currentTimeMillis()); Node node = mock(Node.cla...
public void copyTo(T valueCopy, StreamRecord<T> target) { target.value = valueCopy; target.timestamp = this.timestamp; target.hasTimestamp = this.hasTimestamp; }
@Test void testCopyTo() { StreamRecord<String> recNoTimestamp = new StreamRecord<>("test"); StreamRecord<String> recNoTimestampCopy = new StreamRecord<>(null); recNoTimestamp.copyTo("test", recNoTimestampCopy); assertThat(recNoTimestampCopy).isEqualTo(recNoTimestamp); Stream...
@Override public V peek() { return getValue(0); }
@Test public void testRemoveWithCodec() { RQueue<TestModel> queue = redisson.getQueue("queue"); TestModel msg = new TestModel("key", "traceId", 0L); queue.add(msg); assertThat(queue.contains(queue.peek())).isTrue(); }
@Override public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final SingleRule rule, final Collection<DataNode> includedDataNodes) { Collection<Qualif...
@Test void assertDecideWhenNotContainsSingleTable() { SelectStatementContext select = createStatementContext(); Collection<DataNode> includedDataNodes = new HashSet<>(); assertFalse(new SingleSQLFederationDecider().decide(select, Collections.emptyList(), mock(RuleMetaData.class), createDatab...
public void close() { if (!isClosed) { isClosed = true; unmapAndCloseChannel(); } }
@Test void shouldNotThrowWhenOldRecordingLogsAreDeleted() throws IOException { final File segmentFile = new File(archiveDir, segmentFileName(recordingThreeId, SEGMENT_LENGTH * 2)); try (FileChannel log = FileChannel.open(segmentFile.toPath(), READ, WRITE, CREATE)) { final Byt...
@Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { if (context.validate()) { try { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK...
@Test void testDoInjectForV4Sign() throws Exception { resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); ramContext.setRegionId("cn-hangzhou"); namingResourceInjector.doInject(resour...
@Override public JobResourceRequirements requestJobResourceRequirements() { final JobResourceRequirements.Builder builder = JobResourceRequirements.newBuilder(); for (JobInformation.VertexInformation vertex : jobInformation.getVertices()) { builder.setParallelismForJobVertex( ...
@Test void testRequestDefaultResourceRequirements() throws Exception { final JobGraph jobGraph = createJobGraph(); final Configuration configuration = new Configuration(); final AdaptiveScheduler scheduler = new AdaptiveSchedulerBuilder( jobGra...
public static File zip(String srcPath) throws UtilException { return zip(srcPath, DEFAULT_CHARSET); }
@Test @Disabled public void zipToStreamTest(){ final String zip = "d:/test/testToStream.zip"; final OutputStream out = FileUtil.getOutputStream(zip); ZipUtil.zip(out, new String[]{"sm1_alias.txt"}, new InputStream[]{FileUtil.getInputStream("d:/test/sm4_1.txt")}); }
@Override public String getConfig(final String dataId) { try { return configService.getConfig(dataId, NacosPathConstants.GROUP, NacosPathConstants.DEFAULT_TIME_OUT); } catch (NacosException e) { LOG.error("Get data from nacos error.", e); throw new ShenyuException...
@Test public void testOnSelectorChanged() throws NacosException { when(configService.getConfig(anyString(), anyString(), anyLong())).thenReturn(null); SelectorData selectorData = SelectorData.builder().id(MOCK_ID).name(MOCK_NAME).pluginName(MOCK_PLUGIN_NAME).build(); nacosDataChangedListener...
public String toString() { return "[if " + booleanExpression.toString(0) + "]"; }
@Test public void testIfVertexWithSecretsIsntLeaked() throws InvalidIRException { BooleanExpression booleanExpression = DSL.eEq(DSL.eEventValue("password"), DSL.eValue("${secret_key}")); ConfigVariableExpander cve = ConfigVariableExpanderTest.getFakeCve( Collections.singletonMap("se...
public List<LispTeRecord> getTeRecords() { return ImmutableList.copyOf(records); }
@Test public void testConstruction() { LispTeLcafAddress teLcafAddress = address1; LispIpv4Address rtrRloc1 = new LispIpv4Address(IpAddress.valueOf("192.168.1.1")); LispIpv4Address rtrRloc2 = new LispIpv4Address(IpAddress.valueOf("192.168.1.2")); assertThat("lookup flag value in TeR...
public static DataSchema dataMapToDataSchema(DataMap map, PegasusSchemaParser parser) { // Convert DataMap into DataSchema ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JacksonDataCodec codec = new JacksonDataCodec(); try { codec.writeMap(map, outputStream); } cat...
@Test public void testConvertDataMapToDataSchema() throws IOException { for (String good : goodInputs) { NamedDataSchema dataSchema = (NamedDataSchema) TestUtil.dataSchemaFromString(good); DataMap mapFromString = TestUtil.dataMapFromString(good); PegasusSchemaParser parser = new SchemaPar...
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf, QueuePath childQueuePath) { setTemplateEntriesForChild(conf, childQueuePath, false); }
@Test public void testOneLevelWildcardTemplate() { conf.set(getTemplateKey(TEST_QUEUE_A_WILDCARD, "capacity"), "6w"); AutoCreatedQueueTemplate template = new AutoCreatedQueueTemplate(conf, TEST_QUEUE_AB); template.setTemplateEntriesForChild(conf, TEST_QUEUE_ABC); Assert.assertEquals("weight i...
@Override public byte[] getBytes(final int columnIndex) { return values.getBytes(columnIndex - 1); }
@Test public void shouldGetBytes() { assertThat(row.getBytes("f_bytes"), is(new byte[]{0, 1, 2})); }
public String build(TablePath tablePath) { StringBuilder createTableSql = new StringBuilder(); createTableSql .append("CREATE TABLE ") .append(CatalogUtils.quoteIdentifier(tablePath.getDatabaseName(), fieldIde, "\"")) .append(".") .append(C...
@Test public void testBuild() { String dataBaseName = "test_database"; String tableName = "test_table"; TablePath tablePath = TablePath.of(dataBaseName, tableName); TableSchema tableSchema = TableSchema.builder() .column(PhysicalColumn.of("id",...
@Override public ZonedDateTime createdAt() { return ZonedDateTime.parse("2016-12-15T16:39:00Z"); }
@Test public void createdAt() throws Exception { assertThat(migration.createdAt()).isEqualTo(ZonedDateTime.parse("2016-12-15T16:39:00Z")); }
@Override public long offset() { throw new UnsupportedOperationException("StateStores can't access offset."); }
@Test public void shouldThrowOnOffset() { assertThrows(UnsupportedOperationException.class, () -> context.offset()); }
private int refreshQueues(String subClusterId) throws IOException, YarnException { // Refresh the queue properties ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshQueuesRequest request = recordFactory.newRecordInstance(RefreshQueuesRequest.class); if (StringUti...
@Test public void testRefreshQueues() throws Exception { String[] args = { "-refreshQueues" }; assertEquals(0, rmAdminCLI.run(args)); verify(admin).refreshQueues(any(RefreshQueuesRequest.class)); }
@VisibleForTesting protected void writeToFile( FileObject fileObject, String backupFileName ) throws IOException, KettleException { OutputStream outputStream = null; PrintStream out = null; try { outputStream = initOutputStreamUsingKettleVFS( fileObject ); out = new PrintStream( outputStream ...
@Test public void writeToFileTest() throws KettleException, IOException { doCallRealMethod().when( sharedObjectsMock ).writeToFile( any( FileObject.class ), anyString() ); when( sharedObjectsMock.initOutputStreamUsingKettleVFS( any( FileObject.class ) ) ).thenThrow( new RuntimeException() ); try...
public static boolean isBasicInfoChanged(Member actual, Member expected) { if (null == expected) { return null != actual; } if (!expected.getIp().equals(actual.getIp())) { return true; } if (expected.getPort() != actual.getPort()) { return true...
@Test void testIsBasicInfoChangedForChangedAbilities() { Member newMember = buildMember(); newMember.setGrpcReportEnabled(true); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); }
public static String getDefaultHost(@Nullable String strInterface, @Nullable String nameserver, boolean tryfallbackResolution) throws UnknownHostException { if (strInterface == null || "default".equals(strInterface)) { return cach...
@Test public void testGetLocalHost() throws Exception { String hostname = DNS.getDefaultHost(DEFAULT); assertNotNull(hostname); }
@Override public Object decode(Response response, Type type) throws IOException, DecodeException { if (response.status() == 404 || response.status() == 204) if (JSONObject.class.isAssignableFrom((Class<?>) type)) return new JSONObject(); else if (JSONArray.class.isAssignableFrom((Class<?>) typ...
@Test void emptyBodyDecodesToEmpty() throws IOException { Response response = Response.builder() .status(204) .reason("OK") .headers(Collections.emptyMap()) .body("", UTF_8) .request(request) .build(); assertThat(((JSONObject) new JsonDecoder().decode(response, ...
protected static void handleMigration(ListMultimap<TStorageMedium, Long> tabletMetaMigrationMap, long backendId) { TabletInvertedIndex invertedIndex = GlobalStateMgr.getCurrentState().getTabletInvertedIndex(); AgentBatchTask batchTask = new AgentBatchTask(); ...
@Test public void testHandleMigrationTaskControl() { long backendId = 10001L; // mock the task execution on BE new MockUp<AgentTaskExecutor>() { @Mock public void submit(AgentBatchTask task) { } }; OlapTable olapTable = (OlapTable) Global...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldFillInRowtime() { // Given: final ConfiguredStatement<InsertValues> statement = givenInsertValues( ImmutableList.of(K0, COL0, COL1), ImmutableList.of( new StringLiteral("str"), new StringLiteral("str"), new LongLiteral(2L) ) ...
public static DateTime beginOfWeek(Date date) { return new DateTime(beginOfWeek(calendar(date))); }
@Test public void beginOfWeekTest() { final String dateStr = "2017-03-01 22:33:23"; final DateTime date = DateUtil.parse(dateStr); Objects.requireNonNull(date).setFirstDayOfWeek(Week.MONDAY); // 一周的开始 final Date beginOfWeek = DateUtil.beginOfWeek(date); assertEquals("2017-02-27 00:00:00", beginOfWeek.toSt...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_interpret_select_statement_with_cql_format() { // When intrContext.getLocalProperties().put("outputFormat", "cql"); final InterpreterResult actual = interpreter.interpret( "SELECT * FROM " + ARTISTS_TABLE + " LIMIT 2;", intrContext); intrContext.getLocalProperties().remove("o...
public static String normalize(final String path) { return normalize(path, true); }
@Test public void test972() { assertEquals("//home/path", PathNormalizer.normalize("//home/path")); }
@Override public void write(InputT element, Context context) throws IOException, InterruptedException { while (bufferedRequestEntries.size() >= maxBufferedRequests) { flush(); } addEntryToBuffer(elementConverter.apply(element, context), false); nonBlockingFlush(); }
@Test public void testThatIntermittentlyFailingEntriesShouldBeFlushedWithMainBatchInTimeBasedFlush() throws Exception { AsyncSinkWriterImpl sink = new AsyncSinkWriterImplBuilder() .context(sinkInitContext) .maxBatchSizeInBytes(10_00...
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testDisplayDataInheritanceNamespace() { ExtendsBaseOptions options = PipelineOptionsFactory.as(ExtendsBaseOptions.class); options.setFoo("bar"); DisplayData displayData = DisplayData.from(options); assertThat( displayData, hasDisplayItem( allOf(hasKey("f...
@Override public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment, InstancePartitions instancePartitions, InstancePartitionsType instancePartitionsType) { String serverTag = _tenantConfig.getServer(); Set<String> instances = HelixHelper.getServerInstances...
@Test public void testSegmentAssignmentToRealtimeHosts() { List<HelixProperty> instanceConfigList = new ArrayList<>(); for (String instance : INSTANCES) { ZNRecord znRecord = new ZNRecord(instance); znRecord.setListField(TAG_LIST.name(), ImmutableList.of(REALTIME_SERVER_TAG)); instanceConfig...
@Override public ShardingSphereSchema swapToObject(final YamlShardingSphereSchema yamlConfig) { return Optional.ofNullable(yamlConfig).map(this::swapSchema).orElseGet(() -> new ShardingSphereSchema(yamlConfig.getName())); }
@Test void assertSwapToShardingSphereSchemaWithoutTable() { YamlShardingSphereSchema yamlSchema = YamlEngine.unmarshal(readYAML(YAML_WITHOUT_TABLE), YamlShardingSphereSchema.class); assertTrue(new YamlSchemaSwapper().swapToObject(yamlSchema).getAllTableNames().isEmpty()); }
public static Capacity from(ClusterResources resources) { return from(resources, resources); }
@Test void testCapacityValidation() { // Equal min and max is allowed Capacity.from(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)), new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)), IntRange.empty(), false, ...
@Udf public Long round(@UdfParameter final long val) { return val; }
@Test public void shouldRoundBigDecimalWithDecimalPlacesNegative() { assertThat(udf.round(new BigDecimal("-1.0"), 0), is(new BigDecimal("-1.0"))); assertThat(udf.round(new BigDecimal("-1.1"), 0), is(new BigDecimal("-1.0"))); assertThat(udf.round(new BigDecimal("-1.5"), 0), is(new BigDecimal("-1.0"))); ...
public List<QueryMetadata> sql(final String sql) { return sql(sql, Collections.emptyMap()); }
@Test public void shouldParseStatements() { // When: ksqlContext.sql("Some SQL", SOME_PROPERTIES); // Then: verify(ksqlEngine).parse("Some SQL"); }
@Override public ParsedLine parse(final String line, final int cursor, final ParseContext context) { final ParsedLine parsed = delegate.parse(line, cursor, context); if (context != ParseContext.ACCEPT_LINE) { return parsed; } if (UnclosedQuoteChecker.isUnclosedQuote(line)) { throw new EO...
@Test public void shouldAlwaysAcceptCommentLines() { // Given: givenDelegateWillReturn(" -- this is a comment"); // When: final ParsedLine result = parser.parse("what ever", 0, ParseContext.ACCEPT_LINE); // Then: assertThat(result, is(parsedLine)); }
@Override public void startIt() { if (semaphore.tryAcquire()) { try { executorService.execute(this::doDatabaseMigration); } catch (RuntimeException e) { semaphore.release(); throw e; } } else { LOGGER.trace("{}: lock is already taken or process is already runnin...
@Test public void status_is_SUCCEEDED_and_failure_is_null_when_trigger_runs_without_an_exception() { underTest.startIt(); assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.SUCCEEDED); assertThat(migrationState.getError()).isEmpty(); assertThat(migrationState.getStartedAt(...
public static <T> Window<T> into(WindowFn<? super T, ?> fn) { try { fn.windowCoder().verifyDeterministic(); } catch (NonDeterministicException e) { throw new IllegalArgumentException("Window coders must be deterministic.", e); } return Window.<T>configure().withWindowFn(fn); }
@Test @Category({ValidatesRunner.class, UsesCustomWindowMerging.class}) public void testMergingCustomWindowsWithoutCustomWindowTypes() { Instant startInstant = new Instant(0L); PCollection<KV<String, Integer>> inputCollection = pipeline.apply( Create.timestamped( Timestam...
public static Coordinate gcj02ToBd09(double lng, double lat) { double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * X_PI); double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * X_PI); double bd_lng = z * Math.cos(theta) + 0.0065; double bd_lat = z * Math.sin(theta) + 0.006; return ...
@Test public void gcj02ToBd09Test() { final CoordinateUtil.Coordinate coordinate = CoordinateUtil.gcj02ToBd09(116.404, 39.915); assertEquals(116.41036949371029D, coordinate.getLng(), 0); assertEquals(39.92133699351022D, coordinate.getLat(), 0); }
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) { NewExternalIssue newExternalIssue = sensorContext.newExternalIssue(); newExternalIssue.type(DEFAULT_TYPE); newExternalIssue.engineId(driverName); newExte...
@Test @UseDataProvider("rule_severity_to_sonarqube_severity_mapping") public void mapResult_mapsCorrectlyLevelToSeverity(Result.Level ruleSeverity, Severity sonarQubeSeverity, org.sonar.api.issue.impact.Severity impactSeverity) { NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, ruleSeveri...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefin...
@Test public void testConvertFloat() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("real").dataType("real").build(); Column column = SqlServerTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), c...
@Override public void write(InputT element, Context context) throws IOException, InterruptedException { while (bufferedRequestEntries.size() >= maxBufferedRequests) { flush(); } addEntryToBuffer(elementConverter.apply(element, context), false); nonBlockingFlush(); }
@Test public void testThatABatchWithSizeSmallerThanMaxBatchSizeIsFlushedOnTimeoutExpiry() throws Exception { AsyncSinkWriterImpl sink = new AsyncSinkWriterImplBuilder() .context(sinkInitContext) .maxBatchSize(10) ...
public static void forceMkdir(String path) throws IOException { FileUtils.forceMkdir(new File(path)); }
@Test void testForceMkdir() throws IOException { File dir = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()).toFile(); DiskUtils.forceMkdir(dir); assertTrue(dir.exists()); dir.deleteOnExit(); }
@Override public SCMView responseMessageForSCMView(String responseBody) { try { final Map map = parseResponseToMap(responseBody); if (map.isEmpty()) { throw new RuntimeException("The JSON for SCM View cannot be empty"); } final String display...
@Test public void shouldBuildSCMViewFromResponse() { String jsonResponse = "{\"displayValue\":\"MySCMPlugin\", \"template\":\"<html>junk</html>\"}"; SCMView view = messageHandler.responseMessageForSCMView(jsonResponse); assertThat(view.displayValue(), is("MySCMPlugin")); assertThat...
private RemotingCommand querySubscriptionByConsumer(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); QuerySubscriptionByConsumerRequestHeader requestHeader = (QuerySubsc...
@Test public void testQuerySubscriptionByConsumer() throws RemotingCommandException { QuerySubscriptionByConsumerRequestHeader requestHeader = new QuerySubscriptionByConsumerRequestHeader(); requestHeader.setGroup("group"); requestHeader.setTopic("topic"); RemotingCommand request = R...
@Override public void ensureValid(String name, Object value) { if (value == null || ((List) value).isEmpty()) { throw new ConfigException(name, value, "Empty list"); } }
@Test public void testValidList() { new NonEmptyListValidator().ensureValid("foo", Collections.singletonList("foo")); }
public SalesforceHttpClient getHttpClient() { return httpClient; }
@Test public void usesUserSuppliedHttpClient() { assertEquals(client, component.getHttpClient()); }
@JsonAnyGetter public Map<String, PartitionsSpec> get() { return map; }
@Test public void testPartitionNumbers() { List<Integer> partsANumbers = PARTSA.partitionNumbers(); assertEquals(Integer.valueOf(0), partsANumbers.get(0)); assertEquals(Integer.valueOf(1), partsANumbers.get(1)); assertEquals(Integer.valueOf(2), partsANumbers.get(2)); assertEq...
public boolean cleanTable() { boolean allRemoved = true; Set<String> removedPaths = new HashSet<>(); for (PhysicalPartition partition : table.getAllPhysicalPartitions()) { try { WarehouseManager manager = GlobalStateMgr.getCurrentState().getWarehouseMgr(); ...
@Test public void testRPCFailed(@Mocked LakeTable table, @Mocked PhysicalPartition partition, @Mocked MaterializedIndex index, @Mocked LakeTablet tablet, @Mocked LakeService lakeService) throws St...
ProducerListeners listeners() { return new ProducerListeners(eventListeners.toArray(new HollowProducerEventListener[0])); }
@Test public void testFireValidationStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(validation...
@Override public PostgreSQLPacket getQueryRowPacket() throws SQLException { return new PostgreSQLDataRowPacket(proxyBackendHandler.getRowData().getData()); }
@Test void assertGetQueryRowPacket() throws SQLException { when(proxyBackendHandler.getRowData()).thenReturn(new QueryResponseRow(Collections.emptyList())); PostgreSQLPacket actual = queryExecutor.getQueryRowPacket(); assertThat(actual, is(instanceOf(PostgreSQLDataRowPacket.class))); }
public ConfigurationProperty create(String key, String value, String encryptedValue, Boolean isSecure) { ConfigurationProperty configurationProperty = new ConfigurationProperty(); configurationProperty.setConfigurationKey(new ConfigurationKey(key)); if (isNotBlank(value) && isNotBlank(encrypte...
@Test public void shouldCreateWithValueForAUnsecuredProperty() { Property key = new Property("key"); key.with(Property.SECURE, false); ConfigurationProperty property = new ConfigurationPropertyBuilder().create("key", "value", null, false); assertThat(property.getConfigurationValue(...
public static String removeInvalidChars(String name, String prefix) { String result = removeInvalidCharsMiddle(name); if (!result.isEmpty()) { int codePoint = result.codePointAt(0); if (!isValidIdentifierStart(codePoint)) { return prefix + result; } } return result; }
@Test public void testRemoveInvalidChars() { assertThat(removeInvalidChars("1cls", "C")).isEqualTo("C1cls"); assertThat(removeInvalidChars("-cls", "C")).isEqualTo("cls"); assertThat(removeInvalidChars("A-cls", "C")).isEqualTo("Acls"); }
public synchronized void registerNewConf(Address address, List<ConfigProperty> configList) { Preconditions.checkNotNull(address, "address should not be null"); Preconditions.checkNotNull(configList, "configuration list should not be null"); // Instead of recording property name, we record property key. ...
@Test public void registerNewConf() { ConfigurationStore configStore = createConfigStore(); Map<Address, List<ConfigRecord>> confMap = configStore.getConfMap(); assertTrue(confMap.containsKey(mAddressOne)); assertTrue(confMap.containsKey(mAddressTwo)); }
@Override public void refreshSelectorDataSelf(final List<SelectorData> selectorDataList) { if (CollectionUtils.isEmpty(selectorDataList)) { return; } BaseDataCache.getInstance().cleanSelectorDataSelf(selectorDataList); }
@Test public void testRefreshSelectorDataSelf() { baseDataCache.cleanSelectorData(); SelectorData firstCachedSelectorData = SelectorData.builder().id("1").pluginName(mockPluginName1).build(); SelectorData secondCachedSelectorData = SelectorData.builder().id("2").pluginName(mockPluginName2).b...
static void unregister(MBeanServer server, ObjectName objectName) { try { for (ObjectName name : server.queryNames(objectName, null)) { server.unregisterMBean(name); } } catch (MBeanRegistrationException | InstanceNotFoundException e) { throw new CacheException("Error unregistering " +...
@Test(dataProvider = "unegisterExceptions") public void unregister_error(Class<? extends Throwable> throwableType) throws JMException { var name = new ObjectName(""); MBeanServer server = Mockito.mock(); when(server.queryNames(any(), any())).thenReturn(Set.of(name)); doThrow(throwableType).when(server...
@Override @SuppressWarnings({"unchecked", "rawtypes"}) public RouteContext route(final ConnectionContext connectionContext, final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database) { RouteContext result = new RouteContext(); Optional<String> ...
@Test void assertRouteBySQLCommentHintWithException() { when(hintValueContext.findHintDataSourceName()).thenReturn(Optional.of("ds_3")); QueryContext queryContext = new QueryContext(commonSQLStatementContext, "", Collections.emptyList(), hintValueContext, connectionContext, metaData); assert...
public int tryUnblockFailedWorkflowInstances(String workflowId, int limit, TimelineEvent event) { return withMetricLogError( () -> withRetryableUpdate( UNBLOCK_INSTANCES_FAILED_STATUS, stmt -> { int idx = 0; stmt.setString(++idx...
@Test public void testTryUnblockFailedWorkflowInstances() { wfi.setWorkflowUuid("test-uuid"); wfi.setWorkflowInstanceId(0L); int res = runStrategyDao.startWithRunStrategy(wfi, Defaults.DEFAULT_RUN_STRATEGY); assertEquals(1, res); int cnt = instanceDao.terminateQueuedInstances( ...
public static <InputT> KeyByBuilder<InputT> of(PCollection<InputT> input) { return named(null).of(input); }
@Test public void testBuild_Windowing() { final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings()); final PCollection<KV<String, Long>> counted = SumByKey.of(dataset) .keyBy(s -> s) .valueBy(s -> 1L) .windowBy(FixedWindows.of(org.jo...
@Override public JWK getJwk() { return this.jwk; }
@Test void shouldGetJwk() { var jwk = service.getJwk(); assertEquals("RSA", jwk.getKeyType().getValue()); assertEquals(JWSAlgorithm.RS256, jwk.getAlgorithm()); assertEquals(KeyUse.SIGNATURE, jwk.getKeyUse()); assertEquals(Set.of(SIGN, VERIFY), jwk.getKeyOperations()); }
public void close() { if (isOpen()) { LOG.debug("Closing stream ({})", mDescription); mClosed = true; mRequestObserver.onCompleted(); } }
@Test public void close() throws Exception { mStream.close(); assertTrue(mStream.isClosed()); assertFalse(mStream.isOpen()); verify(mRequestObserver).onCompleted(); }
static String isHostParam(final String given) { final String hostUri = StringHelper.notEmpty(given, "host"); final Matcher matcher = HOST_PATTERN.matcher(given); if (!matcher.matches()) { throw new IllegalArgumentException( "host must be an absolute URI (e.g. ht...
@Test public void emptyHostParamsAreNotAllowed() { assertThrows(IllegalArgumentException.class, () -> RestOpenApiHelper.isHostParam("")); }
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldNotUseSourceTopicForCreateMissingTopic() { // Given: givenStatement("CREATE STREAM x (FOO VARCHAR) WITH(value_format='avro', kafka_topic='topic', partitions=2);"); // When: injector.inject(statement, builder); // Then: verify(builder, never()).withSource(any(), any())...
@Override public Map<K, V> getCachedMap() { return localCacheView.getCachedMap(); }
@Test public void testGetAllCache() { RLocalCachedMap<String, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test")); Map<String, Integer> cache = map.getCachedMap(); map.put("1", 100); map.put("2", 200); map.put("3", 300); map.put("4", 400); ...
@Override public void execute(Context context) { try (CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse()) { while (issues.hasNext()) { DefaultIssue issue = issues.next(); if (shouldUpdateIndexForIssue(issue)) { changedIssuesRepository.addIssueKey(issue.key()); ...
@Test public void execute_whenIssueIsChanged_shouldLoadIssue() { protoIssueCache.newAppender() .append(newDefaultIssue().setChanged(true)) .close(); underTest.execute(mock(ComputationStep.Context.class)); verify(changedIssuesRepository).addIssueKey("issueKey1"); }
public static Float parseFloat(String value) { return parseFloat(value, ZERO_RADIX); }
@Test public void parseFloat() { String floatValStr = floatVal.toString(); Assertions.assertEquals(java.util.Optional.of(floatVal).get(), TbUtils.parseFloat(floatValStr)); String floatValHex = "41EA62CC"; Assertions.assertEquals(0, Float.compare(floatVal, TbUtils.parseHexToFloat(floa...
@VisibleForTesting static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) { ImmutableSortedMap.Builder<OffsetRange, Integer> rval = ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE); List<OffsetRange> sortedRanges = Lists.newArrayList(ranges); if (...
@Test public void testOverlappingTos() { Iterable<OffsetRange> ranges = Arrays.asList(range(0, 12), range(4, 12), range(8, 12)); Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition = computeOverlappingRanges(ranges); assertEquals( ImmutableMap.builder().put(range(0, 4),...
public static Builder builder() { return new Builder(); }
@Test void testPrimaryKeyNoColumns() { assertThatThrownBy( () -> TableSchema.builder() .field("f0", DataTypes.BIGINT()) .primaryKey("pk", new String[] {}) ...
public static boolean classExists(String fqcn) { try { Class.forName(fqcn); return true; } catch (ClassNotFoundException e) { return false; } }
@Test public void testClassExists() { assertTrue(Reflections.classExists(String.class.getName())); assertFalse(Reflections.classExists("com.fake.class")); }
public static ReservationListResponse mergeReservationsList( Collection<ReservationListResponse> responses) { ReservationListResponse reservationListResponse = Records.newRecord(ReservationListResponse.class); List<ReservationAllocationState> reservationAllocationStates = new ArrayList<>()...
@Test public void testMergeReservationsList() { // normal response ReservationListResponse response1 = createReservationListResponse( 165348678000L, 165348690000L, 165348678000L, 1L); ReservationListResponse response2 = createReservationListResponse( 165348750000L, 165348768000L, 1653487...
public List<Supplier<PageProjectionWithOutputs>> compileProjections( SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, Optiona...
@Test public void testCommonSubExpressionLongProjectionList() { PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); List<Supplier<PageProjectionWithOutputs>> pageProjections = functionCompiler.compileProjections(SESSION.getSqlFunctionProperties(), c...
@Override public boolean supportsSchemasInPrivilegeDefinitions() { return false; }
@Test void assertSupportsSchemasInPrivilegeDefinitions() { assertFalse(metaData.supportsSchemasInPrivilegeDefinitions()); }
public <T> T retryable(CheckedSupplier<T> action) throws RetryException { long attempt = 0L; do { try { attempt++; return action.get(); } catch (Exception ex) { logger.error("Backoff retry exception", ex); } ...
@Test @SuppressWarnings("unchecked") public void testExceptionsReachMaxRetry() throws Exception { ExponentialBackoff backoff = new ExponentialBackoff(2L); CheckedSupplier<Boolean> supplier = Mockito.mock(CheckedSupplier.class); Mockito.when(supplier.get()).thenThrow(new IOException("can'...
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type =...
@Test public void applyGeneratesIntegerUsingJavaTypeLongWhenMaximumGreaterThanIntegerMax() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "integer"); objectNod...
@Override public boolean equals(Object o) { if (o == null) return false; if (!o.getClass().equals(ScramCredentialData.class)) return false; ScramCredentialData other = (ScramCredentialData) o; return Arrays.equals(salt, other.salt) && Arrays.equals(storedKey, other.st...
@Test public void testEquals() { assertNotEquals(SCRAMCREDENTIALDATA.get(0), SCRAMCREDENTIALDATA.get(1)); assertNotEquals(SCRAMCREDENTIALDATA.get(1), SCRAMCREDENTIALDATA.get(0)); assertNotEquals(SCRAMCREDENTIALDATA.get(0), SCRAMCREDENTIALDATA.get(2)); assertNotEquals(SCRAMCREDENTIALD...
public boolean submitProcessingErrors(Message message) { return submitProcessingErrorsInternal(message, message.processingErrors()); }
@Test public void submitProcessingErrors_nothingSubmittedAndMessageNotFilteredOut_ifSubmissionDisabledAndDuplicatesAreNotKept() throws Exception { // given final Message msg = Mockito.mock(Message.class); when(msg.getMessageId()).thenReturn("msg-x"); when(msg.supportsFailureHandling(...
public double interpolate(double... x) { if (x.length != this.x[0].length) { throw new IllegalArgumentException(String.format("Invalid input vector size: %d, expected: %d", x.length, this.x[0].length)); } int n = this.x.length; double y = yvi[n]; for (int i = 0; i < ...
@Test public void testInterpolate() { System.out.println("interpolate"); double[][] x = {{0, 0}, {1, 1}}; double[] y = {0, 1}; KrigingInterpolation instance = new KrigingInterpolation(x, y); double[] x1 = {0.5, 0.5}; assertEquals(0, instance.interpolate(x[0]), 1E-7); ...
@Override public void start() throws Exception { if (!state.compareAndSet(State.LATENT, State.STARTED)) { throw new IllegalStateException(); } try { client.create().creatingParentContainersIfNeeded().forPath(queuePath); } catch (KeeperException.NodeExistsExce...
@Test public void testSimple() throws Exception { final int itemQty = 10; DistributedQueue<TestQueueItem> queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { BlockingQueu...
@GuardedBy("lock") private boolean isLeader(ResourceManager<?> resourceManager) { return running && this.leaderResourceManager == resourceManager; }
@Test void grantLeadership_withExistingLeader_stopExistLeader() throws Exception { final UUID leaderSessionId1 = UUID.randomUUID(); final UUID leaderSessionId2 = UUID.randomUUID(); final CompletableFuture<UUID> startRmFuture1 = new CompletableFuture<>(); final CompletableFuture<UUID>...
@Override public String toString() { return "QueryCacheConfig{" + "batchSize=" + batchSize + ", bufferSize=" + bufferSize + ", delaySeconds=" + delaySeconds + ", includeValue=" + includeValue + ", populate=" + populate ...
@Test public void testToString() { QueryCacheConfig config = new QueryCacheConfig(); assertNotNull(config.toString()); assertContains(config.toString(), "QueryCacheConfig"); }
@Override public boolean isClosed() throws SQLException { return _closed; }
@Test public void isClosedTest() throws Exception { PinotConnection pinotConnection = new PinotConnection("dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTransport); Assert.assertFalse(pinotConnection.isClosed()); pinotConnection.close(); Assert.assertTrue...
@SuppressWarnings("unchecked") @Override public boolean canHandleReturnType(Class returnType) { return rxSupportedTypes.stream() .anyMatch(classType -> classType.isAssignableFrom(returnType)); }
@Test public void testCheckTypes() { assertThat(rxJava3RateLimiterAspectExt.canHandleReturnType(Flowable.class)).isTrue(); assertThat(rxJava3RateLimiterAspectExt.canHandleReturnType(Single.class)).isTrue(); }
private void index() { IntStream.range(0, this.size()).forEach(i -> preferences.setProperty(toProperty(this.get(i), prefix), i)); }
@Test public void testIndex() { BookmarkCollection c = new BookmarkCollection(new NullLocal("", "f")) { @Override protected void save(Host bookmark) { assertNotNull(bookmark.getUuid()); } }; final Host d = new Host(new TestProtocol(), "c");...
@Override public void clearUp(ProcessContext context) { RootContext.unbind(); RootContext.unbindBranchType(); if (sagaTransactionalTemplate != null) { GlobalTransaction globalTransaction; StateMachineInstance machineInstance = (StateMachineInstance) context.getVariab...
@Test public void testClearUp() { ProcessContextImpl context = new ProcessContextImpl(); context.setVariable(DomainConstants.VAR_NAME_STATEMACHINE_INST, new StateMachineInstanceImpl()); Assertions.assertDoesNotThrow(() -> dbAndReportTcStateLogStore.clearUp(context)); }
public String saveGitlabConfiguration(GitlabConfiguration gitlabConfiguration) { String body = String.format(""" { "enabled": "%s", "applicationId": "%s", "url": "%s", "secret": "%s", "synchronizeGroups": "%s", "provisioningType": "%s", "...
@Test public void saveGitlabConfiguration_shouldNotFail() { when(wsConnector.call(any()).failIfNotSuccessful().content()).thenReturn("{\"id\": \"configId\"}"); assertThatNoException().isThrownBy(() -> gitlabConfigurationService.saveGitlabConfiguration(new GitlabConfiguration(true, "appId", "url", "secret", ...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STATE: handleLiteralState(c,...
@Test public void testNested() throws ScanException { List<Token> tl = new TokenStream("%(%a%(%b))").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(Token.PERCENT_TOKEN); witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); witness.add(Token.PERCENT_TOKEN); witness.add(new To...
public void write(WriteRequest writeRequest) { if (!tryAcquireSemaphore()) { return; } mSerializingExecutor.execute(() -> { try { if (mContext == null) { LOG.debug("Received write request {}.", RpcSensitiveConfigMask.CREDENTIAL_FIELD_MASKER.maskObjects(LOG, writeR...
@Test public void writeInvalidOffsetLaterRequest() throws Exception { mWriteHandler.write(newWriteRequestCommand(0)); // The write request contains an invalid offset mWriteHandler.write(newWriteRequestCommand(1)); waitForResponses(); checkErrorCode(mResponseObserver, Status.Code.INVALID_ARGUMENT);...
@Nullable static ProxyProvider createFrom(Properties properties) { Objects.requireNonNull(properties, "properties"); if (properties.containsKey(HTTP_PROXY_HOST) || properties.containsKey(HTTPS_PROXY_HOST)) { return createHttpProxyFrom(properties); } if (properties.containsKey(SOCKS_PROXY_HOST)) { return...
@Test void proxyFromSystemProperties_nullProxyProviderIfNoHostnamePropertySet() { Properties properties = new Properties(); ProxyProvider provider = ProxyProvider.createFrom(properties); assertThat(provider).isNull(); }
public void createPlainAccessConfig(final String addr, final PlainAccessConfig plainAccessConfig, final long timeoutMillis) throws RemotingException, InterruptedException, MQClientException { CreateAccessConfigRequestHeader requestHeader = new CreateAccessConfigRequestHeader(); requestHe...
@Test public void testCreatePlainAccessConfig_Exception() throws InterruptedException, RemotingException { doAnswer(mock -> { RemotingCommand request = mock.getArgument(1); return createErrorResponse4UpdateAclConfig(request); }).when(remotingClient).invokeSync(anyString(), an...
public void finish(Promise<Void> aggregatePromise) { ObjectUtil.checkNotNull(aggregatePromise, "aggregatePromise"); checkInEventLoop(); if (this.aggregatePromise != null) { throw new IllegalStateException("Already finished"); } this.aggregatePromise = aggregatePromise...
@SuppressWarnings("unchecked") @Test public void testFinishCalledTwiceThrows() { combiner.finish(p1); assertThrows(IllegalStateException.class, new Executable() { @Override public void execute() { combiner.finish(p1); } }); }
@Override public boolean isOutput() { return false; }
@Test public void testIsOutput() throws Exception { assertFalse( analyzer.isOutput() ); }
public SuperTrendIndicator(final BarSeries series) { this(series, 10, 3d); }
@Test public void testSuperTrendIndicator() { SuperTrendIndicator superTrendIndicator = new SuperTrendIndicator(data); assertNumEquals(this.numOf(15.730621000000003), superTrendIndicator.getValue(4)); assertNumEquals(this.numOf(17.602360938100002), superTrendIndicator.getValue(9)); ...