focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void cluster_not_down_if_more_than_min_count_of_storage_nodes_are_available() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(3) .bringEntireClusterUp() .reportStorageNodeState(0, State.DOWN); final ClusterStateGenerator.Params params = fixture.ge...
public List<Pair<byte[], byte[]>> readRecords() throws IOException { final List<Pair<byte[], byte[]>> commands = new ArrayList<>(); for (final String line : Files.readAllLines(getFile().toPath(), StandardCharsets.UTF_8)) { final String commandId = line.substring(0, line.indexOf(KEY_VALUE_SEPARATOR_STR)); ...
@Test public void shouldBeEmptyWhenReadAllCommandsFromEmptyFile() throws IOException { // When final List<?> commands = replayFile.readRecords(); // Then assertThat(commands.size(), is(0)); }
@Override public InputChannel getChannel(int channelIndex) { int gateIndex = inputChannelToInputGateIndex[channelIndex]; return inputGatesByGateIndex .get(gateIndex) .getChannel(channelIndex - inputGateChannelIndexOffsets[gateIndex]); }
@Test void testUpdateInputChannel() throws Exception { final SingleInputGate inputGate1 = createInputGate(1); TestInputChannel inputChannel1 = new TestInputChannel(inputGate1, 0); inputGate1.setInputChannels(inputChannel1); final SingleInputGate inputGate2 = createInputGate(1); ...
@GetMapping("/all") public ShenyuAdminResult queryAllPlugins() { List<PluginData> pluginDataList = pluginService.listAll(); return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, pluginDataList); }
@Test public void testQueryAllPlugins() throws Exception { given(this.pluginService.listAll()) .willReturn(new ArrayList<>()); this.mockMvc.perform(MockMvcRequestBuilders.get("/plugin/all")) .andExpect(status().isOk()) .andReturn(); }
public static int min(int a, int b, int c) { return Math.min(Math.min(a, b), c); }
@Test public void testMin_3args() { System.out.println("min"); int a = -1; int b = 0; int c = 1; int expResult = -1; int result = MathEx.min(a, b, c); assertEquals(expResult, result); }
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_map_of_serializable_key_and_value_with_null() { Map<String, SerializableObject> original = new LinkedHashMap<>(); original.put("null", null); original.put("key", new SerializableObject("value")); Object cloned = serializer.clone(original); asser...
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to( Class<OutputT> clazz) { return to(TypeDescriptor.of(clazz)); }
@Test @Category(NeedsRunner.class) public void testFromRowsUnboxingRow() { PCollection<POJO1Nested> pojos = pipeline .apply(Create.of(new POJO1())) .apply(Select.fieldNames("field3")) .apply(Convert.to(TypeDescriptor.of(POJO1Nested.class))); PAssert.that(pojos).co...
public static void appendPrettyHexDump(final StringBuilder dump, final DirectBuffer buffer) { appendPrettyHexDump(dump, buffer, 0, buffer.capacity()); }
@Test void shouldPrettyPrintHex() { final String contents = "Hello World!\nThis is a test String\nto print out."; final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(); buffer.putStringAscii(0, contents); final StringBuilder builder = new StringBuilder(); Pri...
public static XmlXStream getInstance() { return s_instance; }
@Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidElementUnmarshalling() throws Exception { XStream xstream = XmlXStream.getInstance(); xstream.fromXML("<void/>"); }
@Override public int compareTo(Resource other) { checkArgument(other != null && getClass() == other.getClass() && name.equals(other.name)); return value.compareTo(other.value); }
@Test void testCompareToFailDifferentName() { // initialized as different anonymous classes final Resource resource1 = new TestResource("name1", 0.0); final Resource resource2 = new TestResource("name2", 0.0); assertThatThrownBy(() -> resource1.compareTo(resource2)) ....
@Override public void unsubscribeService(Service service, Subscriber subscriber, String clientId) { Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service); Client client = clientManager.getClient(clientId); checkClientIsLegal(client, clientId); ...
@Test void testUnSubscribeWhenClientNull() { assertThrows(NacosRuntimeException.class, () -> { when(clientManager.getClient(anyString())).thenReturn(null); // Excepted exception ephemeralClientOperationServiceImpl.unsubscribeService(service, subscriber, ipPortBasedClientI...
@Override public boolean isEmpty() { return sideInputs.isEmpty(); }
@Test public void testIsEmptyFalse() { PCollectionView<Iterable<String>> view = Pipeline.create().apply(Create.of("1")).apply(View.asIterable()); SideInputHandler sideInputHandler = new SideInputHandler(ImmutableList.of(view), InMemoryStateInternals.<Void>forKey(null)); assertFalse(sideIn...
@ApiOperation(value = "Get all Widget types for specified Bundle (getBundleWidgetTypes)", notes = "Returns an array of Widget Type objects that belong to specified Widget Bundle." + WIDGET_TYPE_DESCRIPTION + " " + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_...
@Test public void testGetBundleWidgetTypes() throws Exception { WidgetsBundle widgetsBundle = new WidgetsBundle(); widgetsBundle.setTitle("My widgets bundle"); widgetsBundle = doPost("/api/widgetsBundle", widgetsBundle, WidgetsBundle.class); List<WidgetType> widgetTypes = new ArrayL...
long nextPullOffset(MessageQueue remoteQueue) { if (!pullOffsetTable.containsKey(remoteQueue)) { try { pullOffsetTable.putIfAbsent(remoteQueue, rocketmqPullConsumer.fetchConsumeOffset(remoteQueue, false)); } catch (MQClientException e) { ...
@Test public void testNextPullOffset() throws Exception { MessageQueue messageQueue = new MessageQueue(); when(rocketmqPullConsume.fetchConsumeOffset(any(MessageQueue.class), anyBoolean())) .thenReturn(123L); assertThat(localMessageCache.nextPullOffset(new MessageQueue())).isEqua...
@Nonnull public static RestClientBuilder client() { return client("localhost", DEFAULT_PORT); }
@Test public void given_clientAsString_whenReadFromElasticSource_thenFinishSuccessfully() { ElasticsearchContainer container = ElasticSupport.elastic.get(); String httpHostAddress = container.getHttpHostAddress(); indexDocument("my-index", of("name", "Frantisek")); Pipeline p = Pip...
public void asyncAddData(T data, AddDataCallback callback, Object ctx){ if (!batchEnabled){ if (state == State.CLOSING || state == State.CLOSED){ callback.addFailed(BUFFERED_WRITER_CLOSED_EXCEPTION, ctx); return; } ByteBuf byteBuf = dataSeriali...
@Test public void testMetricsStatsThatTriggeredByLargeSingleData() throws Exception { // Use TwoLenSumDataSerializer for: write a little data once, then write a large data once. int bytesSizePerRecordWhichInBatch = 4; int batchedWriteMaxSize = 1024; TwoLenSumDataSerializer dataSerial...
@Override public void execute(EventNotificationContext ctx) throws EventNotificationException { final SlackEventNotificationConfig config = (SlackEventNotificationConfig) ctx.notificationConfig(); LOG.debug("SlackEventNotification backlog size in method execute is [{}]", config.backlogSize()); ...
@Test(expected = EventNotificationException.class) public void executeWithInvalidWebhookUrl() throws EventNotificationException, JsonProcessingException { givenGoodNotificationService(); givenSlackClientThrowsPermException(); //when execute is called with a invalid webhook URL, we expect a e...
@Produces @DefaultBean @Singleton public JobRequestScheduler jobRequestScheduler(StorageProvider storageProvider) { if (jobRunrBuildTimeConfiguration.jobScheduler().enabled()) { return new JobRequestScheduler(storageProvider, emptyList()); } return null; }
@Test void jobRequestSchedulerIsNotSetupWhenConfigured() { when(jobSchedulerBuildTimeConfiguration.enabled()).thenReturn(false); assertThat(jobRunrProducer.jobRequestScheduler(storageProvider)).isNull(); }
int parseAndConvert(String[] args) throws Exception { Options opts = createOptions(); int retVal = 0; try { if (args.length == 0) { LOG.info("Missing command line arguments"); printHelp(opts); return 0; } CommandLine cliParser = new GnuParser().parse(opts, args); ...
@Test public void testConvertFSConfigurationErrorHandling2() throws Exception { setupFSConfigConversionFiles(true); String[] args = getArgumentsAsArrayWithDefaults("-f", FSConfigConverterTestCommons.FS_ALLOC_FILE, "-r", FSConfigConverterTestCommons.CONVERSION_RULES_FILE, "-p"); FSConfigTo...
@Override public int getDefaultTransactionIsolation() { return 0; }
@Test void assertGetDefaultTransactionIsolation() { assertThat(metaData.getDefaultTransactionIsolation(), is(0)); }
public static <T> void accept(Consumer<T> consumer, T target) { if (consumer != null) { consumer.accept(target); } }
@Test public void testConsumer() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); CommonUtils.accept(param -> atomicBoolean.set(param == SLEEP_TIME), SLEEP_TIME); assertTrue(atomicBoolean.get()); }
public void setLanguage(String languageString) { Set<String> invalidCodes = new HashSet<>(); Set<String> validCodes = new HashSet<>(); getLangs(languageString, validCodes, invalidCodes); if (!invalidCodes.isEmpty()) { throw new IllegalArgumentException("Invalid language code(...
@Test public void testBadLanguageCode() throws Exception { TesseractOCRConfig tesseractOCRConfig = new TesseractOCRConfig(); assertThrows(IllegalArgumentException.class, () -> { tesseractOCRConfig.setLanguage("kerplekistani"); }); }
@Override public int unlink(String path) { return AlluxioFuseUtils.call(LOG, () -> rmInternal(path), FuseConstants.FUSE_UNLINK, "path=%s", path); }
@Test @DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu") @Ignore public void unlink() throws Exception { AlluxioURI expectedPath = BASE_EXPECTED_URI.join("/foo/bar"); doNothing().when(mFileSystem).delete(expectedPath); mFuseFs.unlink("/foo/bar"); verify(mFileSystem).delete(e...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType; String colName = null...
@Test public void testAggregateMultipleStatsWhenSomeNullValues() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2"); ColumnStatisticsData data1 = new ColStatsBuilder<>(long.class).numNulls(1).numDVs(2) .low(1L).high(2L).hll(1, 2).build(); ColumnStatisticsData data2 =...
@Override public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) { String githubApiUrl = characteristics.get(DEVOPS_PLATFORM_URL); String githubRepository = characteristics.get(DEVOPS_PLATFORM_PROJECT_IDENTIFIER); if (githubApiUrl == null ||...
@Test public void getDevOpsProjectCreator_whenOneValidAlmSettingAndPublicByDefaultAndAutoProvisioningEnabled_shouldInstantiateDevOpsProjectCreatorAndDefineAnAuthAppToken() { AlmSettingDto almSettingDto = mockAlmSettingDto(true); mockSuccessfulGithubInteraction(); when(projectDefaultVisibility.get(any())....
@Override public QueryHeader build(final QueryResultMetaData queryResultMetaData, final ShardingSphereDatabase database, final String columnName, final String columnLabel, final int columnIndex) throws SQLException { String schemaName = null == database ? "" : database.getName()...
@Test void assertBuild() throws SQLException { QueryResultMetaData queryResultMetaData = createQueryResultMetaData(); QueryHeader actual = new MySQLQueryHeaderBuilder().build(queryResultMetaData, createDatabase(), queryResultMetaData.getColumnName(1), queryResultMetaData.getColumnLabel(1), 1); ...
public static Config getConfig( Configuration configuration, @Nullable HostAndPort externalAddress) { return getConfig( configuration, externalAddress, null, PekkoUtils.getForkJoinExecutorConfig( ActorSystemBoots...
@Test void getConfigCustomKeyOrTruststoreType() { final Configuration configuration = new Configuration(); configuration.set(SecurityOptions.SSL_INTERNAL_ENABLED, true); configuration.set(SecurityOptions.SSL_INTERNAL_KEYSTORE_TYPE, "JKS"); configuration.set(SecurityOptions.SSL_INTERN...
public static long addClamped(long a, long b) { long sum = a + b; return sumHadOverflow(a, b, sum) ? (a >= 0 ? Long.MAX_VALUE : Long.MIN_VALUE) : sum; }
@Test public void when_addClamped_then_doesNotOverflow() { // no overflow assertEquals(0, addClamped(0, 0)); assertEquals(1, addClamped(1, 0)); assertEquals(-1, addClamped(-1, 0)); assertEquals(-1, addClamped(Long.MAX_VALUE, Long.MIN_VALUE)); assertEquals(-1, addClamp...
@Override public int handleBeat(String namespaceId, String serviceName, String ip, int port, String cluster, RsInfo clientBeat, BeatInfoInstanceBuilder builder) throws NacosException { Service service = getService(namespaceId, serviceName, true); String clientId = IpPortBasedClient.getCl...
@Test void testHandleBeat() throws NacosException { IpPortBasedClient ipPortBasedClient = Mockito.mock(IpPortBasedClient.class); when(clientManager.getClient(Mockito.anyString())).thenReturn(ipPortBasedClient); when(ipPortBasedClient.getAllPublishedService()).thenReturn(Collections....
public static Expression convert(Filter[] filters) { Expression expression = Expressions.alwaysTrue(); for (Filter filter : filters) { Expression converted = convert(filter); Preconditions.checkArgument( converted != null, "Cannot convert filter to Iceberg: %s", filter); expression =...
@Test public void testNotIn() { Not filter = Not.apply(In.apply("col", new Integer[] {1, 2})); Expression actual = SparkFilters.convert(filter); Expression expected = Expressions.and(Expressions.notNull("col"), Expressions.notIn("col", 1, 2)); Assert.assertEquals("Expressions should match", ex...
public void setFilePaths(String... filePaths) { Path[] paths = new Path[filePaths.length]; for (int i = 0; i < paths.length; i++) { paths[i] = new Path(filePaths[i]); } setFilePaths(paths); }
@Test void testSinglePathGetOnMultiPathIF() { final MultiDummyFileInputFormat format = new MultiDummyFileInputFormat(); final String myPath = "/an/imaginary/path"; final String myPath2 = "/an/imaginary/path2"; format.setFilePaths(myPath, myPath2); assertThatThrownBy(format::...
public float get(int index) { return nonzeros[index]; }
@Test public void testGet() { System.out.println("get"); assertEquals(0.9, sparse.get(0, 0), 1E-7); assertEquals(0.8, sparse.get(2, 2), 1E-7); assertEquals(0.5, sparse.get(1, 1), 1E-7); assertEquals(0.0, sparse.get(2, 0), 1E-7); assertEquals(0.0, sparse.get(0, 2), 1E-...
static CommitMeta buildCommitMetadata(String commitMsg, Map<String, String> catalogOptions) { return catalogOptions(CommitMeta.builder().message(commitMsg), catalogOptions).build(); }
@Test public void testAuthorIsNullWithoutJvmUser() { String jvmUserName = System.getProperty("user.name"); try { System.clearProperty("user.name"); CommitMeta commitMeta = NessieUtil.buildCommitMetadata("commit msg", ImmutableMap.of()); assertThat(commitMeta.getAuthor()).isNull(); } fina...
public static String normalize(String string) { if (string == null) { return null; } if (string.length() > 63) { string = string.substring(0, 63); } string = StringUtils.stripEnd(string, "-"); string = StringUtils.stripEnd(string, "."); s...
@Test void normalize() { assertThat(ScriptService.normalize(null), nullValue()); assertThat(ScriptService.normalize("a-normal-string"), is("a-normal-string")); assertThat(ScriptService.normalize("very.very.very.very.very.very.very.very.very.very.very.very.long.namespace"), is("very.very.very...
static Map<String, ValueExtractor> instantiateExtractors(List<AttributeConfig> attributeConfigs, ClassLoader classLoader) { Map<String, ValueExtractor> extractors = createHashMap(attributeConfigs.size()); for (AttributeConfig config : attribut...
@Test public void instantiate_extractors_wrongType() { // GIVEN AttributeConfig string = new AttributeConfig("iq", "java.lang.String"); // WHEN assertThatThrownBy(() -> instantiateExtractors(singletonList(string))) .isInstanceOf(IllegalArgumentException.class); }
@Override public int getRootComponentRef() { checkState(rootComponentRef.isInitialized(), "Root component ref has not been set"); return rootComponentRef.getProperty(); }
@Test public void getRootComponentRef() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setRootComponentRef(10); assertThat(underTest.getRootComponentRef()).isEqualTo(10); }
@Override public void replay( long offset, long producerId, short producerEpoch, CoordinatorRecord record ) throws RuntimeException { ApiMessageAndVersion key = record.key(); ApiMessageAndVersion value = record.value(); switch (key.version()) { ...
@Test public void testReplayConsumerGroupMemberMetadataWithNullValue() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class); CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetr...
@Description("converts the string to upper case") @ScalarFunction("upper") @LiteralParameters("x") @SqlType("char(x)") public static Slice charUpper(@SqlType("char(x)") Slice slice) { return upper(slice); }
@Test public void testCharUpper() { assertFunction("UPPER(CAST('' AS CHAR(10)))", createCharType(10), padRight("", 10)); assertFunction("UPPER(CAST('Hello World' AS CHAR(11)))", createCharType(11), padRight("HELLO WORLD", 11)); assertFunction("UPPER(CAST('what!!' AS CHAR(6)))", createCha...
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { String path = ((HttpServletRequest) req).getRequestURI().replaceFirst(((HttpServletRequest) req).getContextPath(), ""); MAX_AGE_BY_PATH.entrySet().stream() .filter(m -> pat...
@Test public void does_nothing_on_home() throws Exception { HttpServletRequest request = newRequest("/"); underTest.doFilter(request, response, chain); verifyNoInteractions(response); }
public MountTable getMountPoint(final String path) throws IOException { verifyMountTable(); return findDeepest(RouterAdmin.normalizeFileSystemPath(path)); }
@Test public void testGetMountPointOfConsecutiveSlashes() throws IOException { // Check get the mount table entry for a path MountTable mtEntry; mtEntry = mountTable.getMountPoint("///"); assertEquals("/", mtEntry.getSourcePath()); mtEntry = mountTable.getMountPoint("///user//"); assertEquals...
public static Object construct(Object something) throws Exception { if (something instanceof String) { return Class.forName((String)something).getConstructor().newInstance(); } else if (something instanceof Map) { // keys are the class name, values are the parameters. ...
@Test(expected = Exception.class) public void classWithoutMatchedConstructor_constructed_failsWhenNoDefault() throws Exception { Map<String, List<Map<String, Object>>> constructMap = new HashMap<>(); List<Map<String, Object>> params = new ArrayList<>(); params.add(Collections.singletonMap("j...
@Override public void init(final InternalProcessorContext<Void, Void> context) { super.init(context); this.context = context; try { keySerializer = prepareKeySerializer(keySerializer, context, this.name()); } catch (ConfigException | StreamsException e) { thro...
@Test public void shouldThrowStreamsExceptionOnUndefinedKeySerde() { utilsMock.when(() -> WrappingNullableUtils.prepareKeySerializer(any(), any(), any())) .thenThrow(new ConfigException("Please set StreamsConfig#DEFAULT_KEY_SERDE_CLASS_CONFIG")); final Throwable exception = assertThrows...
public Connection getConnection() { return getConfig().isShared() ? pooledConnection() : singleUseConnection(); }
@Test public void shared_connection_should_be_initialized_lazy() { jdbcDataConnection = new JdbcDataConnection(new DataConnectionConfig() .setName(TEST_NAME) .setProperty("jdbcUrl", "invalid-jdbc-url") .setShared(true)); assertThatThrownBy(() -> jdbcD...
public static RuntimeException wrapIf(boolean condition, Throwable t) { if (condition) { return wrap(t); } if (t instanceof RuntimeException) { return (RuntimeException) t; } return new RuntimeException(t); }
@Test public void testWrapIfOnlyWrapsWhenTrue() { IOException cause = new IOException(); RuntimeException wrapped = UserCodeException.wrapIf(true, cause); assertThat(wrapped, is(instanceOf(UserCodeException.class))); }
@CheckForNull static BundleParams getBundleParameters(String restOfPath) { if (restOfPath == null || restOfPath.length() == 0) { return null; } String[] pathTokens = restOfPath.split("/"); List<String> bundleParameters = new ArrayList<>(); for (String pathToken ...
@Test public void test_getBundleParameters_invalid_url() { Assert.assertNull(BlueI18n.getBundleParameters("pluginx/1.0.0")); Assert.assertNull(BlueI18n.getBundleParameters("/pluginx/1.0.0")); }
public static Schema inferSchema(Object value) { if (value instanceof String) { return Schema.STRING_SCHEMA; } else if (value instanceof Boolean) { return Schema.BOOLEAN_SCHEMA; } else if (value instanceof Byte) { return Schema.INT8_SCHEMA; } else if (...
@Test public void shouldInferNoSchemaForMapContainingObject() { Schema listSchema = Values.inferSchema(Collections.singletonMap(new Object(), new Object())); assertNull(listSchema); }
@Deprecated public Map<String, Object> get() { return CLIENT_ATTACHMENT.get().get(); }
@Test public void testClearAttachmentMap() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put(...
@Override public boolean shouldCareAbout(Object entity) { return securityConfigClasses.stream().anyMatch(aClass -> aClass.isAssignableFrom(entity.getClass())); }
@Test public void shouldCareAboutSecurityAuthConfigChange() { SecurityConfigChangeListener securityConfigChangeListener = new SecurityConfigChangeListener() { @Override public void onEntityConfigChange(Object entity) { } }; assertThat(securityConfigChange...
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldGetCorrectLocationsComplexCtas() { // Given: final String statementString = // 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 "CREATE TABLE customer_bookings\n" + ...
@VisibleForTesting static void createDocumentationFile( String title, DocumentingRestEndpoint restEndpoint, RestAPIVersion apiVersion, Path outputFile) throws IOException { final OpenAPI openApi = createDocumentation(title, restEndpoint, apiVersion...
@Test void testDuplicateOperationIdsAreRejected(@TempDir Path tmpDir) { final Path file = tmpDir.resolve("openapi_spec.yaml"); assertThatThrownBy( () -> OpenApiSpecGenerator.createDocumentationFile( "titl...
public static <T extends Comparable<T>> void assertTypeValid( Column<T> foundColumn, PrimitiveTypeName primitiveType) { Class<T> foundColumnType = foundColumn.getColumnType(); ColumnPath columnPath = foundColumn.getColumnPath(); Set<PrimitiveTypeName> validTypeDescriptors = classToParquetType.get(fou...
@Test public void testUnsupportedType() { try { assertTypeValid(invalidColumn, PrimitiveTypeName.INT32); fail("This should throw!"); } catch (IllegalArgumentException e) { assertEquals( "Column invalid.column was declared as type: " + "org.apache.parquet.filter2.predi...
public static void checkServiceNameFormat(String combineServiceName) { String[] split = combineServiceName.split(Constants.SERVICE_INFO_SPLITER); if (split.length <= 1) { throw new IllegalArgumentException( "Param 'serviceName' is illegal, it should be format as 'groupNam...
@Test void testCheckServiceNameFormat() { String validServiceName = "group@@serviceName"; NamingUtils.checkServiceNameFormat(validServiceName); }
public void shutdown(final Callback<None> callback) { _managerStarted = false; for (ZooKeeperAnnouncer server : _servers) { server.shutdown(); } Callback<None> zkCloseCallback = new CallbackAdapter<None, None>(callback) { @Override protected None convertResponse(None none) th...
@Test public void testMarkDownDuringDisconnection() throws Exception { ZooKeeperAnnouncer announcer = getZooKeeperAnnouncer(_cluster, _uri, WEIGHT); ZooKeeperConnectionManager manager = createManager(true, announcer); ZooKeeperEphemeralStore<UriProperties> store = createAndStartUriStore(); Uri...
public static boolean isIPv6(String addr) { return InetAddressValidator.isIPv6Address(removeBrackets(addr)); }
@Test void testIsIPv6() { assertTrue(InternetAddressUtil.isIPv6("[::1]")); assertFalse(InternetAddressUtil.isIPv6("127.0.0.1")); assertFalse(InternetAddressUtil.isIPv6("er34234")); }
@Override public int hashCode() { return Objects.hash(status, causes, details); }
@Test public void hashcode_is_based_on_content() { NodeHealth.Builder builder = testSupport.randomBuilder(); NodeHealth underTest = builder.build(); assertThat(builder.build().hashCode()) .isEqualTo(underTest.hashCode()); }
@Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { status.setChecksum(write.checksum(file, status).compute(new NullInputStream(0L), status)); return super.touch(file, status); }
@Test public void testTouchFileStartWithDot() throws Exception { final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, String.format(".%s.", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.file)); ...
public static Map<String, String> inputFiles(RunContext runContext, Object inputs) throws Exception { return FilesService.inputFiles(runContext, Collections.emptyMap(), inputs); }
@Test void overrideExistingInputFile() throws Exception { RunContext runContext = runContextFactory.of(); FilesService.inputFiles(runContext, Map.of("file.txt", "content")); FilesService.inputFiles(runContext, Map.of("file.txt", "overriden content")); String fileContent = FileUtils...
@Udf(description = "Returns the inverse (arc) tangent of y / x") public Double atan2( @UdfParameter( value = "y", description = "The ordinate (y) coordinate." ) final Integer y, @UdfParameter( value = "x", descriptio...
@Test public void shouldHandleZeroYPositiveX() { assertThat(udf.atan2(0.0, 0.24), closeTo(0.0, 0.000000000000001)); assertThat(udf.atan2(0.0, 7.1), closeTo(0.0, 0.000000000000001)); assertThat(udf.atan2(0, 3), closeTo(0.0, 0.000000000000001)); assertThat(udf.atan2(0L, 2L), closeTo(0.0, 0.0000000000000...
@Override public void showPreviewForKey( Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) { KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme); Point previewPosition = mPositionCalculator.calculatePositionForPreview( key, previ...
@Test public void testNoPopupWhenTextSizeIsZero() { mTheme.setPreviewKeyTextSize(0); KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); Assert.assertNull(getLatestCreatedPopupWindow()); underTest.showPreviewForKey(mTestKeys[0], "y", mKeybo...
@Override public void pluginJarUpdated(BundleOrPluginFileDetails bundleOrPluginFileDetails) { final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails); try { LOGGER.info("Plugin update starting: {}", bundleOrPluginFileDetails.fil...
@Test void shouldNotTryAndUpdateManifestOfAnUpdatedInvalidPlugin() throws Exception { DefaultPluginJarChangeListener spy = spy(listener); String pluginId = "plugin-id"; File pluginFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME); copyPluginToTheDirectory(pluginWorkDir, PLUGIN_JAR...
@Override public MplsLabel decode(int value) { return MplsLabel.mplsLabel(value); }
@Test public void testDecode() { assertThat(sut.decode(100), is(MplsLabel.mplsLabel(100))); }
public static Event[] fromJson(final String json) throws IOException { return fromJson(json, BasicEventFactory.INSTANCE); }
@Test(expected=IOException.class) public void testFromJsonWithInvalidJsonString() throws Exception { Event.fromJson("gabeutch"); }
@Override public Set<Device> allocateDevices(Set<Device> availableDevices, int count, Map<String, String> env) { // Can consider topology, utilization.etc Set<Device> allocated = new HashSet<>(); int number = 0; for (Device d : availableDevices) { allocated.add(d); number++; if...
@Test public void testAllocateSingleDevice() throws ResourceHandlerException, IOException { setupTestDirectoryWithScript(); plugin = new NECVEPlugin(envProvider, defaultSearchDirs, udevUtil); Set<Device> available = new HashSet<>(); Device device = getTestDevice(0); available.add(device); ...
@Override public void run() { updateElasticSearchHealthStatus(); updateFileSystemMetrics(); }
@Test public void when_elasticsearch_yellow_status_is_updated_to_green() { ClusterHealthResponse clusterHealthResponse = new ClusterHealthResponse(); clusterHealthResponse.setStatus(ClusterHealthStatus.YELLOW); when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse); underTest.run(); ...
@VisibleForTesting protected Collection<StreamsMetadata> getStreamsMetadata() { if (sharedRuntimesEnabled && kafkaStreams instanceof KafkaStreamsNamedTopologyWrapper) { return ((KafkaStreamsNamedTopologyWrapper) kafkaStreams) .streamsMetadataForStore(storeName, queryId); } return kafkaStr...
@Test public void shouldUseNamedTopologyWhenSharedRuntimeIsEnabledForStreamsMetadataForStore() { // Given: final KsLocator locator = new KsLocator(STORE_NAME, kafkaStreamsNamedTopologyWrapper, topology, keySerializer, LOCAL_HOST_URL, true, "queryId"); // When: locator.getStreamsMetadata(); ...
static <PojoT extends SdkPojo, BuilderT extends SdkBuilder<BuilderT, PojoT> & SdkPojo> AwsBuilderFactory<PojoT, BuilderT> builderFactory(Class<PojoT> clazz) { Generic pojoType = new ForLoadedType(clazz).asGenericType(); MethodDescription builderMethod = pojoType.getDeclaredMethods().filter(named(...
@Test public void generateBuilderFactory() { AwsBuilderFactory<SendMessageRequest, SendMessageRequest.Builder> factory = AwsSchemaUtils.builderFactory(SendMessageRequest.class); assertThat(factory.getClass().getPackage()).isEqualTo(SendMessageRequest.class.getPackage()); assertThat(factory.get())...
@Override public MoveApplicationAcrossQueuesResponse moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest request) throws YarnException, IOException { if (request == null || request.getApplicationId() == null || request.getTargetQueue() == null) { routerMetrics.incrMoveApplicationAcro...
@Test public void testMoveApplicationAcrossQueues() throws Exception { LOG.info("Test FederationClientInterceptor : MoveApplication AcrossQueues request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing moveApplicationAcrossQueues request " + "or applicationId or target ...
public static int[] computePhysicalIndices( List<TableColumn> logicalColumns, DataType physicalType, Function<String, String> nameRemapping) { Map<TableColumn, Integer> physicalIndexLookup = computePhysicalIndices(logicalColumns.stream(), physicalType, nameRe...
@Test void testFieldMappingReordered() { int[] indices = TypeMappingUtils.computePhysicalIndices( TableSchema.builder() .field("f1", DataTypes.BIGINT()) .field("f0", DataTypes.STRING()) ...
public Range<PartitionKey> handleNewSinglePartitionDesc(Map<ColumnId, Column> schema, SingleRangePartitionDesc desc, long partitionId, boolean isTemp) throws DdlException { Range<PartitionKey> range; try { range = checkAndCreateRang...
@Test(expected = DdlException.class) public void testSmallInt() throws DdlException, AnalysisException { Column k1 = new Column("k1", new ScalarType(PrimitiveType.SMALLINT), true, null, "", ""); partitionColumns.add(k1); singleRangePartitionDescs.add(new SingleRangePartitionDesc(false, "p1"...
@Override public BufferBuilder requestBufferBlocking(Object owner) { checkIsInitialized(); reclaimBuffersIfNeeded(0); MemorySegment memorySegment = bufferQueue.poll(); if (memorySegment == null) { memorySegment = requestBufferBlockingFromPool(); } if (me...
@Test void testRecycleBuffersAfterPoolSizeDecreased() throws IOException { int numBuffers = 10; BufferPool bufferPool = globalPool.createBufferPool(1, numBuffers); TieredStorageMemoryManagerImpl storageMemoryManager = createStorageMemoryManager( buffe...
@Override public Collection<String> getLogicTableNames() { return logicalTableMapper; }
@Test void assertGetLogicTableMapper() { assertThat(new LinkedList<>(ruleAttribute.getLogicTableNames()), is(Collections.singletonList("foo_tbl"))); }
public Connection connection(Connection connection) { // It is common to implement both interfaces if (connection instanceof XAConnection) { return xaConnection((XAConnection) connection); } return TracingConnection.create(connection, this); }
@Test void connection_wrapsXaInput() { abstract class Both implements XAConnection, Connection { } assertThat(jmsTracing.connection(mock(Both.class))) .isInstanceOf(XAConnection.class); }
public MaterializedConfiguration getConfiguration() { MaterializedConfiguration conf = new SimpleMaterializedConfiguration(); FlumeConfiguration fconfig = getFlumeConfiguration(); AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName()); if (agentConf != null) { ...
@Test public void testReusableChannelNotReusedLater() throws Exception { String agentName = "agent1"; Map<String, String> propertiesReusable = getPropertiesForChannel(agentName, RecyclableChannel.class .getName()); Map<String, String> propertiesDispoab...
public static long getProcessId(final long fallback) { // Note: may fail in some JVM implementations // therefore fallback has to be provided // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); ...
@Test public void test_getProcessId() { long pid = Utils.getProcessId(-1); assertNotEquals(-1, pid); System.out.println("test pid:" + pid); }
@Override public void execute(Runnable command) { _delegateExecutor.execute(toAccountingRunnable(command)); }
@Test public void testBoundsWithinThreadCount() throws BrokenBarrierException, InterruptedException { SchedulerGroupAccountant accountant = mock(SchedulerGroupAccountant.class); // Test below relies on jobs > limit final int limit = 3; final int jobs = 5; // we want total threads > limit ...
public Organization getOrganizationById(Long id) { Optional<Organization> conf = organizationRepository.findById(id); if (!conf.isPresent()) { throw new NotFoundException("Could not find organization with id: " + id); } return conf.get(); }
@Test public void getOrganizationById() { Optional<Organization> organizationOptional = Optional.of(newOrganization()); when(repositoryMock.findById(anyLong())).thenReturn(organizationOptional); Organization result = organizationServiceMock.getOrganizationById(1L); verify(repositor...
public void start() { configService.addListener(configListener); interfaceService.addListener(interfaceListener); setUpConnectivity(); }
@Test public void testNoPeerInterface() { IpAddress ip = IpAddress.valueOf("1.1.1.1"); bgpSpeakers.clear(); bgpSpeakers.add(new BgpConfig.BgpSpeakerConfig(Optional.of("foo"), VlanId.NONE, s1Eth100, Collections.singleton(ip))); reset(interfaceService); interfac...
public Table getTable(String dbName, String tableName) { return get(tableCache, DatabaseTableName.of(dbName, tableName)); }
@Test public void testGetTransactionalTable() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); // get insert only table com.starrocks.catalog.Table table = cachingHiveMetastor...
@SuppressWarnings("unchecked") public static <T> T initialize(Map<String, String> properties) { String factoryImpl = PropertyUtil.propertyAsString(properties, S3FileIOProperties.CLIENT_FACTORY, null); if (Strings.isNullOrEmpty(factoryImpl)) { return (T) AwsClientFactories.from(properties); }...
@Test public void testS3FileIOImplCatalogPropertyDefined() { Map<String, String> properties = Maps.newHashMap(); properties.put( S3FileIOProperties.CLIENT_FACTORY, "org.apache.iceberg.aws.s3.DefaultS3FileIOAwsClientFactory"); Object factoryImpl = S3FileIOAwsClientFactories.initialize(prope...
public char charAt(final int index) { if (index < 0 || index >= length) { throw new StringIndexOutOfBoundsException("index=" + index + " length=" + length); } return (char)buffer.getByte(offset + index); }
@Test void shouldThrowExceptionWhenCharAtCalledWithNoBuffer() { assertThrows(StringIndexOutOfBoundsException.class, () -> asciiSequenceView.charAt(0)); }
static ApiError validateQuotaKeyValue( Map<String, ConfigDef.ConfigKey> validKeys, String key, double value ) { // Ensure we have an allowed quota key ConfigDef.ConfigKey configKey = validKeys.get(key); if (configKey == null) { return new ApiError(Errors.I...
@Test public void testValidateQuotaKeyValueForNegativeQuota() { assertEquals(new ApiError(Errors.INVALID_REQUEST, "Quota consumer_byte_rate must be greater than 0"), ClientQuotaControlManager.validateQuotaKeyValue( VALID_CLIENT_ID_QUOTA_KEYS, "consumer_byte_rate", -2.0)); }
@Override public String buildRemoteURL(String baseRepositoryURL, String referencePath) { // Rebuild a downloadable URL to retrieve file. String remoteUrl = baseRepositoryURL.substring(0, baseRepositoryURL.lastIndexOf("/")); String pathToAppend = referencePath; while (pathToAppend.startsWith("...
@Test void testBuildRemoteURL() { SimpleReferenceURLBuilder builder = new SimpleReferenceURLBuilder(); assertEquals("https://raw.githubusercontent.com/microcks/microcks/main/samples/schema-ref.yml", builder.buildRemoteURL(BASE_URL, "schema-ref.yml")); assertEquals("https://raw.githubus...
public static InstrumentedThreadFactory defaultThreadFactory(MetricRegistry registry, String name) { return new InstrumentedThreadFactory(Executors.defaultThreadFactory(), registry, name); }
@Test public void testDefaultThreadFactoryWithName() throws Exception { final ThreadFactory threadFactory = InstrumentedExecutors.defaultThreadFactory(registry, "tf"); threadFactory.newThread(new NoopRunnable()); assertThat(registry.meter("tf.created").getCount()).isEqualTo(1L); fi...
List<Integer> getClosingTagsOffsets() { return closingTagsOffsets; }
@Test public void should_extract_upper_bounds_from_serialized_rules() { List<Integer> offsets = decorationDataHolder.getClosingTagsOffsets(); assertThat(offsets.get(0)).isEqualTo(8); assertThat(offsets.get(1)).isEqualTo(52); assertThat(offsets.get(2)).isEqualTo(67); assertThat(offsets.get(3)).is...
public static boolean isSystemGroup(String group) { if (StringUtils.isBlank(group)) { return false; } String groupInLowerCase = group.toLowerCase(); for (String prefix : SYSTEM_GROUP_PREFIX_LIST) { if (groupInLowerCase.startsWith(prefix)) { return ...
@Test public void testIsSystemGroup_NonSystemGroup_ReturnsFalse() { String group = "FooGroup"; boolean result = BrokerMetricsManager.isSystemGroup(group); assertThat(result).isFalse(); }
@Override public long get(long key1, int key2) { return super.get0(key1, key2); }
@Test public void testGet() { final long key1 = randomKey(); final int key2 = randomKey(); final SlotAssignmentResult slot = insert(key1, key2); assertTrue(slot.isNew()); final long valueAddress2 = hsa.get(key1, key2); assertEquals(slot.address(), valueAddress2); ...
@VisibleForTesting void updateQueues(String args, SchedConfUpdateInfo updateInfo) { if (args == null) { return; } ArrayList<QueueConfigInfo> queueConfigInfos = new ArrayList<>(); for (String arg : args.split(";")) { queueConfigInfos.add(getQueueConfigInfo(arg)); } updateInfo.setUpd...
@Test(timeout = 10000) public void testUpdateQueuesWithCommaInValue() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.updateQueues("root.a:a1=a1Val1\\,a1Val2 a1Val3,a2=a2Val1\\,a2Val2", schedUpdateInfo); List<QueueConfigInfo> updateQueueInfo = schedUpdateInfo .getUpd...
public static FST<Long> buildFST(SortedMap<String, Integer> input) throws IOException { PositiveIntOutputs fstOutput = PositiveIntOutputs.getSingleton(); FSTCompiler.Builder<Long> fstCompilerBuilder = new FSTCompiler.Builder<>(FST.INPUT_TYPE.BYTE4, fstOutput); FSTCompiler<Long> fstCompiler = fstCompil...
@Test public void testFSTBuilder() throws IOException { SortedMap<String, Integer> x = new TreeMap<>(); x.put("hello-world", 12); x.put("hello-world123", 21); x.put("still", 123); FST<Long> fst = FSTBuilder.buildFST(x); File outputFile = new File(TEMP_DIR, "test.lucene"); FileOutput...
@Override @Cacheable(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE, key = "#code", unless = "#result == null") public NotifyTemplateDO getNotifyTemplateByCodeFromCache(String code) { return notifyTemplateMapper.selectByCode(code); }
@Test public void testGetNotifyTemplateByCodeFromCache() { // mock 数据 NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); notifyTemplateMapper.insert(dbNotifyTemplate); // 准备参数 String code = dbNotifyTemplate.getCode(); // 调用 NotifyTemplate...
@Override public void trace(String msg) { logger.trace(msg); }
@Test void testTrace() { jobRunrDashboardLogger.trace("trace"); verify(slfLogger).trace("trace"); }
@Override public void apply(IntentOperationContext<ProtectionEndpointIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); List<ProtectionEndpointIntent> uninstallIntents = context.intentsToUninstall(); Lis...
@Test public void testUninstallIntents() { List<Intent> intentsToUninstall = createProtectionIntents(CP2); List<Intent> intentsToInstall = Lists.newArrayList(); IntentData toUninstall = new IntentData(createP2PIntent(), IntentState.INSTALLING, ...
static void setConstructor(final String segmentName, final String generatedClassName, final ConstructorDeclaration constructorDeclaration, final String kiePMMLModelClass, final boolean isInterpret...
@Test void setConstructorNoInterpreted() { ConstructorDeclaration constructorDeclaration = MODEL_TEMPLATE.getDefaultConstructor().get(); String segmentName = "SEGMENTNAME"; String generatedClassName = "GENERATEDCLASSNAME"; String kiePMMLModelClass = "KIEPMMLMODELCLASS"; doubl...
@Override public ValueRange range(TemporalField field) { return offsetTime.range(field); }
@Test void range() { Arrays.stream(ChronoField.values()).filter(offsetTime::isSupported) .forEach(field -> assertEquals(offsetTime.range(field), zoneTime.range(field))); }
@Override public double p(double x) { double e = Math.exp(-(x - mu) / scale); return e / (scale * (1.0 + e) * (1.0 + e)); }
@Test public void testP() { System.out.println("p"); LogisticDistribution instance = new LogisticDistribution(2.0, 1.0); instance.rand(); assertEquals(0.1050736, instance.p(0.001), 1E-7); assertEquals(0.1057951, instance.p(0.01), 1E-7); assertEquals(0.1131803, instanc...
@SuppressWarnings("WeakerAccess") public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) { final Map<String, Object> consumerProps = getCommonConsumerConfigs(); // Get main consumer override configs final Map<String, Object> mainC...
@Test public void shouldAllowSettingConsumerIsolationLevelIfEosDisabled() { props.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, READ_UNCOMMITTED.toString()); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> consumerConfigs = streamsConfig.getMainConsumerCo...
public static boolean isAllInventoryTasksFinished(final Collection<PipelineTask> inventoryTasks) { if (inventoryTasks.isEmpty()) { log.warn("inventoryTasks is empty"); } return inventoryTasks.stream().allMatch(each -> each.getTaskProgress().getPosition() instanceof IngestFinishedPosi...
@Test void assertAllInventoryTasksAreFinishedWhenNotAllTasksAreFinished() { AtomicReference<IngestPosition> finishedPosition = new AtomicReference<>(new IngestFinishedPosition()); AtomicReference<IngestPosition> unfinishedPosition = new AtomicReference<>(new IngestPlaceholderPosition()); Inv...
public static void optimize(Pipeline pipeline) { // Compute which Schema fields are (or conversely, are not) accessed in a pipeline. FieldAccessVisitor fieldAccessVisitor = new FieldAccessVisitor(); pipeline.traverseTopologically(fieldAccessVisitor); // Find transforms in this pipeline which both: 1. s...
@Test public void testSourceDoesNotImplementPushdownProjector() { Pipeline p = Pipeline.create(); SimpleSource source = new SimpleSource(FieldAccessDescriptor.withFieldNames("foo", "bar", "baz")); p.apply(source) .apply(new FieldAccessTransform(FieldAccessDescriptor.withFieldNames("foo", "...
public static Boolean getBoolean(Map<String, Object> map, String name) { return getValue(map, name, Boolean.class, "a boolean"); }
@Test public void testGetBooleanParameter() throws Exception { Map<String, Object> o = makeCloudDictionary(); Assert.assertTrue(getBoolean(o, "singletonBooleanKey", false)); Assert.assertFalse(getBoolean(o, "missingKey", false)); try { getBoolean(o, "emptyKey", false); Assert.fail("shoul...
public static Properties getProperties(File file) throws AnalysisException { try (BufferedReader utf8Reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) { return getProperties(utf8Reader); } catch (IOException | IllegalArgumentException e) { throw new Analysi...
@Test public void getProperties_should_support_colon_in_headerValue() throws IOException { String payload = "Metadata-Version: 2.2\r\n" + "Description: My value contains a : colon\r\n"; Properties props = PyPACoreMetadataParser.getProperties(new BufferedReader(new StringRead...
public static AggregationUnit create(final AggregationType type, final boolean isDistinct) { switch (type) { case MAX: return new ComparableAggregationUnit(false); case MIN: return new ComparableAggregationUnit(true); case SUM: ...
@Test void assertCreateDistinctCountAggregationUnit() { assertThat(AggregationUnitFactory.create(AggregationType.COUNT, true), instanceOf(DistinctCountAggregationUnit.class)); }