focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test public void testToStringIPv4() { Ip4Prefix ipPrefix; ipPrefix = Ip4Prefix.valueOf("1.2.3.0/24"); assertThat(ipPrefix.toString(), is("1.2.3.0/24")); ipPrefix = Ip4Prefix.valueOf("1.2.3.4/24"); assertThat(ipPrefix.toString(), is("1.2.3.0/24")); ipPrefix = Ip4Pr...
@Override public TGetTablesInfoResponse getTablesInfo(TGetTablesInfoRequest request) throws TException { return InformationSchemaDataSource.generateTablesInfoResponse(request); }
@Test public void testGetTablesInfo() throws Exception { starRocksAssert.withDatabase("test_table").useDatabase("test_table") .withTable("CREATE TABLE `t1` (\n" + " `k1` date NULL COMMENT \"\",\n" + " `v1` int(11) NULL COMMENT \"\",\n" + ...
public Result runIndexOrPartitionScanQueryOnOwnedPartitions(Query query) { Result result = runIndexOrPartitionScanQueryOnOwnedPartitions(query, true); assert result != null; return result; }
@Test public void verifyIndexedQueryFailureWhileMigrating() { map.addIndex(IndexType.HASH, "this"); EqualPredicate predicate = new EqualPredicate("this", value); mapService.beforeMigration(new PartitionMigrationEvent(MigrationEndpoint.SOURCE, partitionId, 0, 1, UUID.randomUUID())); ...
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } var result = collection.find(Filters.and( Filters.eq("config.type", "aggregation-v1"), ...
@Test public void doesNotRunAgainIfMigrationHadCompletedBefore() { when(clusterConfigService.get(V20230629140000_RenameFieldTypeOfEventDefinitionSeries.MigrationCompleted.class)) .thenReturn(new V20230629140000_RenameFieldTypeOfEventDefinitionSeries.MigrationCompleted()); this.migra...
@Udf public <T extends Comparable<? super T>> List<T> arraySortDefault(@UdfParameter( description = "The array to sort") final List<T> input) { return arraySortWithDirection(input, "ASC"); }
@Test public void shouldSortBools() { final List<Boolean> input = Arrays.asList(true, false, false); final List<Boolean> output = udf.arraySortDefault(input); assertThat(output, contains(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE)); }
public static void notNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } }
@Test void testNotNullWhenInputNotNull2() { notNull(new Object(), new IllegalStateException("null object")); }
@Override public boolean accept(final Path file) { if(list.find(new SimplePathPredicate(file)) != null) { return true; } for(Path f : list) { if(f.isChild(file)) { return true; } } if(log.isDebugEnabled()) { log....
@Test public void testAcceptFileVersions() { final RecursiveSearchFilter f = new RecursiveSearchFilter(new AttributedList<>(Arrays.asList(new Path("/f", EnumSet.of(Path.Type.file))))); assertTrue(f.accept(new Path("/f", EnumSet.of(Path.Type.file), new PathAttributes().withVersionId("1")))); }
@Override public Map<K, V> loadAll(Collection<K> keys) { awaitSuccessfulInit(); Object[] keysArray = keys.toArray(); String sql = queries.loadAll(keys.size()); try (SqlResult queryResult = sqlService.execute(sql, keysArray)) { Iterator<SqlRow> it = queryResult.iterator(...
@Test public void givenRowAndIdColumn_whenLoadAll_thenReturnGenericRecord() { ObjectSpec spec = objectProvider.createObject(mapName, true); objectProvider.insertItems(spec, 1); Properties properties = new Properties(); properties.setProperty(DATA_CONNECTION_REF_PROPERTY, TEST_DATABA...
@Override public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException { LOGGER.debug("Interpret code: {}", st); this.z.setInterpreterContext(context); this.z.setGui(context.getGui()); this.z.setNoteGui(context.getNoteGui()); // set ClassLoader of cu...
@Test void testBatchWordCount() throws InterpreterException, IOException { InterpreterContext context = getInterpreterContext(); InterpreterResult result = interpreter.interpret( "val data = benv.fromElements(\"hello world\", \"hello flink\", \"hello hadoop\")", context); assertEquals(...
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Histogram histogram = registry.histogram(metricsName); Long value = endpoint.getValue(); Long fin...
@Test public void testProcessValueNotSet() throws Exception { Object action = null; when(endpoint.getValue()).thenReturn(null); producer.doProcess(exchange, endpoint, registry, METRICS_NAME); inOrder.verify(exchange, times(1)).getIn(); inOrder.verify(registry, times(1)).histo...
public static HbaseSinkConfig load(String yamlFile) throws IOException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); return mapper.readValue(new File(yamlFile), HbaseSinkConfig.class); }
@Test public final void loadFromYamlFileTest() throws IOException { File yamlFile = getFile("sinkConfig.yaml"); String path = yamlFile.getAbsolutePath(); HbaseSinkConfig config = HbaseSinkConfig.load(path); assertNotNull(config); assertEquals("hbase-site.xml", config.getHbase...
public static Write write() { return new AutoValue_MongoDbIO_Write.Builder() .setMaxConnectionIdleTime(60000) .setBatchSize(1024L) .setSslEnabled(false) .setIgnoreSSLCertificate(false) .setSslInvalidHostNameAllowed(false) .setOrdered(true) .build(); }
@Test public void testWrite() { final String collectionName = "testWrite"; final int numElements = 1000; pipeline .apply(Create.of(createDocuments(numElements, false))) .apply( MongoDbIO.write() .withUri("mongodb://localhost:" + port) .withDatab...
private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = invocationHelper.newResponse(request); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); ...
@Test public void testWeakCounterOps() { String name = "weak-test"; createCounter(name, CounterConfiguration.builder(CounterType.WEAK).initialValue(5).build()); RestCounterClient counterClient = client.counter(name); CompletionStage<RestResponse> response = counterClient.increment(); ...
public boolean isSecurityEnabled() { return securityAuthConfigs != null && !securityAuthConfigs.isEmpty(); }
@Test public void shouldNotSaySecurityEnabledIfSecurityHasNoAuthenticatorsDefined() { ServerConfig serverConfig = new ServerConfig(); assertFalse(serverConfig.isSecurityEnabled(), "Security should not be enabled by default"); }
public RingbufferStoreConfig setClassName(@Nonnull String className) { this.className = checkHasText(className, "Ringbuffer store class name must contain text"); this.storeImplementation = null; return this; }
@Test public void testEqualsAndHashCode() { assumeDifferentHashCodes(); EqualsVerifier.forClass(RingbufferStoreConfig.class) .suppress(Warning.NONFINAL_FIELDS) .withPrefabValues(RingbufferStoreConfigReadOnly.class, new Ringbuf...
public Collection<? extends MqttProperty> listAll() { IntObjectHashMap<MqttProperty> props = this.props; if (props == null && subscriptionIds == null && userProperties == null) { return Collections.<MqttProperty>emptyList(); } if (subscriptionIds == null && userProperties == ...
@Test public void testListAll() { MqttProperties props = createSampleProperties(); List<MqttProperties.MqttProperty> expectedProperties = new ArrayList<MqttProperties.MqttProperty>(); expectedProperties.add(new MqttProperties.IntegerProperty(PAYLOAD_FORMAT_INDICATOR.value(), 6)); ex...
@Override public void run() throws InvalidInputException { String tableType = _input.getTableType(); if ((tableType.equalsIgnoreCase(REALTIME) || tableType.equalsIgnoreCase(HYBRID))) { _output.setAggregateMetrics(shouldAggregate(_input)); } }
@Test public void testRunWithGroupBy() throws Exception { Set<String> metrics = ImmutableSet.of("a", "b", "c"); InputManager input = createInput(metrics, "select d1, d2, sum(a), sum(b) from tableT group by d1, d2"); ConfigManager output = new ConfigManager(); AggregateMetricsRule rule = new Aggr...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path f : files.keySet()) { try { new FilesApi(new BrickApiClient(session)).deleteFilesPath( StringUtils...
@Test @Ignore public void testDeleteRecursively() throws Exception { final Path room = new BrickDirectoryFeature(session).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); final Path folder = new...
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.2"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName();...
@Test public void testImportAccessTokens() throws IOException, ParseException { String expiration1 = "2014-09-10T22:49:44.090+00:00"; Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); when(mockedClient1.getClientId()).then...
boolean isTaskManagerRegistered(ResourceID taskManagerId) { return registeredTaskManagers.contains(taskManagerId); }
@Test void testUnknownTaskManagerRegistration() throws Exception { try (DeclarativeSlotPoolService declarativeSlotPoolService = createDeclarativeSlotPoolService()) { final ResourceID unknownTaskManager = ResourceID.generate(); assertThat( ...
public static boolean isTracerKey(String key) { return key.startsWith(PREFIX); }
@Test public void isTracerKey() { Assert.assertTrue(HttpTracerUtils.isTracerKey(RemotingConstants.RPC_TRACE_NAME + ".xx")); Assert.assertFalse(HttpTracerUtils.isTracerKey("rpc_trace_context111.xx")); }
@PostConstruct public void validateAndSetDefaults() { if (clusters != null) { validateClusterNames(); flattenClusterProperties(); setMetricsDefaults(); } }
@Test void ifOnlyOneClusterProvidedNameIsOptionalAndSetToDefault() { ClustersProperties properties = new ClustersProperties(); properties.getClusters().add(new ClustersProperties.Cluster()); properties.validateAndSetDefaults(); assertThat(properties.getClusters()) .element(0) .extrac...
@Override public boolean add(ResourceConfig resourceConfig) { if (this.contains(resourceConfig) || isBlank(resourceConfig.getName())) { return false; } super.add(resourceConfig); return true; }
@Test public void shouldIgnoreCaseNamesOfResources() { ResourceConfigs resourceConfigs = new ResourceConfigs(); resourceConfigs.add(new ResourceConfig("Eoo")); resourceConfigs.add(new ResourceConfig("eoo")); assertThat(resourceConfigs.size(), is(1)); }
public static <K, E> Collector<E, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) { return unorderedIndex(keyFunction, Function.identity()); }
@Test public void unorderedIndex_with_valueFunction_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(unorderedIndex(s -> null, MyObj::getText))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); }
public String compile(final String xls, final String template, int startRow, int startCol) { return compile( xls, template, InputType.XLS, startRow, ...
@Test public void testLoadSpecificWorksheet() { final String drl = converter.compile("/data/MultiSheetDST.drl.xls", "Another Sheet", "/templates/test_template1.drl", 11, ...
@VisibleForTesting Date calcMostRecentDateForDeletion(@NonNull Date currentDate) { return minusHours(currentDate, numberOfHoursAfterPlayback); }
@Test public void testCalcMostRecentDateForDeletion() throws Exception { APCleanupAlgorithm algo = new APCleanupAlgorithm(24); Date curDateForTest = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("2018-11-13T14:08:56-0800"); Date resExpected = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:s...
@Override public Local find() { final NSFileManager manager = NSFileManager.defaultManager(); final NSURL group = manager .containerURLForSecurityApplicationGroupIdentifier(identifier); if(null == group) { log.warn("Missing com.apple.security.application-groups in...
@Test public void testFind() { assertNotNull(new SecurityApplicationGroupSupportDirectoryFinder().find()); assertEquals("~/Library/Group Containers/G69SCX94XU.duck/Library/Application Support/duck", new SecurityApplicationGroupSupportDirectoryFinder().find().getAbbreviatedPath()); ...
boolean canFilterPlayer(String playerName) { boolean isMessageFromSelf = playerName.equals(client.getLocalPlayer().getName()); return !isMessageFromSelf && (config.filterFriends() || !client.isFriended(playerName, false)) && (config.filterFriendsChat() || !isFriendsChatMember(playerName)) && (config.filte...
@Test public void testMessageFromSelfIsNotFiltered() { when(localPlayer.getName()).thenReturn("Swampletics"); assertFalse(chatFilterPlugin.canFilterPlayer("Swampletics")); }
@Override public void validate(final String name, final Object value) { if (immutableProps.contains(name)) { throw new IllegalArgumentException(String.format("Cannot override property '%s'", name)); } final Consumer<Object> validator = HANDLERS.get(name); if (validator != null) { validato...
@Test public void shouldThrowOnNoneOffsetReset() { // When: final IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> validator.validate(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none") ); // Then: assertThat(e.getMessage(), containsString( "'n...
public String substring(final int beginIndex) { split(); final int beginChar = splitted.get(beginIndex); return input.substring(beginChar); }
@Test public void testSubstringGrapheme() { final UnicodeHelper lh = new UnicodeHelper("a", Method.GRAPHEME); assertEquals("a", lh.substring(0)); final UnicodeHelper lh2 = new UnicodeHelper(new String(Character.toChars(0x1f600)), Method.GRAPHEME); assertEquals(new String(Character....
@Override public Registry getRegistry(URL url) { if (registryManager == null) { throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. " + "Please check if `setApplicationModel` has been override."); } Registry def...
@Test void testRegistryFactoryGroupCache() { Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa")); Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":...
@VisibleForTesting static Set<Platform> getPlatformsSet(RawConfiguration rawConfiguration) throws InvalidPlatformException { Set<Platform> platforms = new LinkedHashSet<>(); for (PlatformConfiguration platformConfiguration : rawConfiguration.getPlatforms()) { Optional<String> architecture = platfo...
@Test public void testGetPlatformsSet_osMissing() { TestPlatformConfiguration platform = new TestPlatformConfiguration("testArchitecture", null); Mockito.<List<?>>when(rawConfiguration.getPlatforms()).thenReturn(Arrays.asList(platform)); InvalidPlatformException exception = assertThrows( ...
@Override public void checkBeforeUpdate(final CreateEncryptRuleStatement sqlStatement) { if (!sqlStatement.isIfNotExists()) { checkDuplicateRuleNames(sqlStatement); } checkColumnNames(sqlStatement); checkAlgorithmTypes(sqlStatement); checkToBeCreatedEncryptors(sql...
@Test void assertCheckSQLStatementWithConflictColumnNames() { EncryptRule rule = mock(EncryptRule.class); when(rule.getConfiguration()).thenReturn(getCurrentRuleConfiguration()); executor.setRule(rule); assertThrows(InvalidRuleConfigurationException.class, () -> executor.checkBeforeU...
@Override public Bitmap clone() { return Bitmap.fromBytes(length, bitSet.toByteArray()); }
@Test public static void testClone() { Bitmap bitmapA = Bitmap.fromBytes(100 * 8, BYTE_STRING_A); Bitmap bitmapB = bitmapA.clone(); // all bits should match for (int i = 0; i < 100 * 8; i++) { assertEquals(bitmapA.getBit(i), bitmapB.getBit(i)); } // ...
@VisibleForTesting void writeInjectedKtr( String targetFilPath ) throws KettleException { if ( shouldWriteToFilesystem() ) { writeInjectedKtrToFs( targetFilPath ); } else { writeInjectedKtrToRepo( targetFilPath ); } }
@Test public void writeInjectedKtrKeepsDataTest() throws Exception { String filepath = "filepath"; metaInject.writeInjectedKtr( filepath ); //Make sure realClone( false ) is called and no other, so that the resulting ktr keeps all the info verify( data.transMeta, times( 1 ) ).realClone( false ); v...
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertMapMessageToAmqpMessageWithByteArrayValueInBody() throws Exception { final byte[] byteArray = new byte[] { 1, 2, 3, 4, 5 }; ActiveMQMapMessage outbound = createMapMessage(); outbound.setBytes("bytes", byteArray); outbound.onSend(); outbound.store...
@Override public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) { if (client.getId() != null) { // if it's not null, it's already been saved, this is an error throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId()); } if (client.getRegisteredRedi...
@Test public void saveNewClient_yesOfflineAccess() { ClientDetailsEntity client = new ClientDetailsEntity(); Set<String> grantTypes = new HashSet<>(); grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); client = service.saveNewClient(client); assertThat(client.getScope().contains(SystemS...
@GetMapping("/api/v1/meetings/{uuid}/sharing") public MomoApiResponse<MeetingSharingResponse> findMeetingSharing(@PathVariable String uuid) { MeetingSharingResponse response = meetingService.findMeetingSharing(uuid); return new MomoApiResponse<>(response); }
@DisplayName("약속 공유 정보를 조회하면 200OK와 응답을 반환한다.") @Test void findMeetingSharing() { Meeting meeting = meetingRepository.save(MeetingFixture.DINNER.create()); RestAssured.given().log().all() .contentType(ContentType.JSON) .when().get("/api/v1/meetings/{uuid}/sharing...
@CheckForNull public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) { if (sourceLine == null) { return null; } DecorationDataHolder decorationDataHolder = new DecorationDataHolder(); if (StringUtils.isNotBlank(highlighting)) ...
@Test public void should_ignore_empty_rule() { String sourceLine = "@Deprecated"; String highlighting = "0,0,a;0,11,a"; String symbols = "1,11,1"; assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo("<span class=\"a\">@<span class=\"sym-1 sym\">Deprecated<...
public void attempts() { try { requireJob(); } catch (Exception e) { renderText(e.getMessage()); return; } if (app.getJob() != null) { try { String taskType = $(TASK_TYPE); if (taskType.isEmpty()) { throw new RuntimeException("missing task-type."); ...
@Test public void testAttempts() { appController.getProperty().remove(AMParams.TASK_TYPE); when(job.checkAccess(any(UserGroupInformation.class), any(JobACL.class))) .thenReturn(false); appController.attempts(); verify(appController.response()).setContentType(MimeType.TEXT); assertEquals...
public Value parse(String json) { return this.delegate.parse(json); }
@Test public void testExponentialFloat() throws Exception { final JsonParser parser = new JsonParser(); final Value msgpackValue = parser.parse("1.234512E4"); assertTrue(msgpackValue.getValueType().isNumberType()); assertTrue(msgpackValue.getValueType().isFloatType()); assert...
public long getPositiveMillisOrDefault(HazelcastProperty property) { return getPositiveMillisOrDefault(property, Long.parseLong(property.getDefaultValue())); }
@Test public void getPositiveMillisOrDefaultWithManualDefault() { String name = ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(); config.setProperty(name, "-300"); HazelcastProperties properties = new HazelcastProperties(config); HazelcastProperty property = new HazelcastPrope...
public final ResourceSkyline getResourceSkyline() { return resourceSkyline; }
@Test public final void testStringToUnixTimestamp() throws ParseException { final long submissionTime = logParserUtil.stringToUnixTimestamp("17/07/16 16:27:25"); Assert.assertEquals(jobMetaData.getResourceSkyline().getJobSubmissionTime(), submissionTime); }
@Override public Dataset<Row> apply(JavaSparkContext jsc, SparkSession sparkSession, Dataset<Row> rowDataset, TypedProperties properties) { String transformerSQL = getStringWithAltKeys(properties, SqlTransformerConfig.TRANSFORMER_SQL); try { // tmp table name doesn't like dashes String tmpT...
@Test public void testSqlQuery() { SparkSession spark = SparkSession .builder() .config(getSparkConfForTest(TestSqlQueryBasedTransformer.class.getName())) .getOrCreate(); JavaSparkContext jsc = JavaSparkContext.fromSparkContext(spark.sparkContext()); // prepare test data Str...
@VisibleForTesting static String getDefaultBaseImage(ProjectProperties projectProperties) throws IncompatibleBaseImageJavaVersionException { if (projectProperties.isWarProject()) { return "jetty"; } int javaVersion = projectProperties.getMajorJavaVersion(); if (javaVersion <= 8) { re...
@Test public void testGetDefaultBaseImage_warProject() throws IncompatibleBaseImageJavaVersionException { when(projectProperties.isWarProject()).thenReturn(true); assertThat(PluginConfigurationProcessor.getDefaultBaseImage(projectProperties)) .isEqualTo("jetty"); }
@Override public void writeInt(final int v) throws IOException { ensureAvailable(INT_SIZE_IN_BYTES); Bits.writeInt(buffer, pos, v, isBigEndian); pos += INT_SIZE_IN_BYTES; }
@Test public void testWriteIntForPositionV() throws Exception { int expected = 100; out.writeInt(1, expected); int actual = Bits.readIntB(out.buffer, 1); assertEquals(expected, actual); }
@Override public List<URL> lookup(URL url) { if (url == null) { throw new IllegalArgumentException("lookup url == null"); } try { checkDestroyed(); List<String> providers = new ArrayList<>(); for (String path : toCategoriesPath(url)) { ...
@Test void testLookupIllegalUrl() { try { zookeeperRegistry.lookup(null); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("lookup url == null")); } }
public boolean matchesBeacon(Beacon beacon) { // All identifiers must match, or the corresponding region identifier must be null. for (int i = mIdentifiers.size(); --i >= 0; ) { final Identifier identifier = mIdentifiers.get(i); Identifier beaconIdentifier = null; if ...
@Test public void testBeaconMatchesRegionWithDifferentIdentifier1() { Beacon beacon = new AltBeacon.Builder().setId1("1").setId2("2").setId3("3").setRssi(4) .setBeaconTypeCode(5).setTxPower(6).setBluetoothAddress("1:2:3:4:5:6").build(); Region region = new Region("myRegion", Identifi...
@Override public Path calcPath(int from, int to) { setupFinishTime(); fromNode = from; endNode = findEndNode(from, to); if (endNode < 0 || isWeightLimitExceeded()) { Path path = createEmptyPath(); path.setFromNode(fromNode); path.setEndNode(endNode...
@Test public void testIssue182() { BaseGraph graph = createGHStorage(); initGraph(graph); Path p = calcPath(graph, 0, 8); assertEquals(IntArrayList.from(0, 7, 8), p.calcNodes()); // expand SPT p = calcPath(graph, 0, 10); assertEquals(IntArrayList.from(0, 1, 2...
@Override public String serializeRow(SeaTunnelRow row) { switch (row.getRowKind()) { case INSERT: case UPDATE_AFTER: return serializeUpsert(row); case UPDATE_BEFORE: case DELETE: return serializeDelete(row); default:...
@Test public void testSerializeUpsertWithoutKey() { String index = "st_index"; Map<String, Object> confMap = new HashMap<>(); confMap.put(SinkConfig.INDEX.key(), index); ReadonlyConfig pluginConf = ReadonlyConfig.fromMap(confMap); ElasticsearchClusterInfo clusterInfo = ...
@Override public byte[] toByteArray() { // write last chunk message id MessageIdData msgId = super.writeMessageIdData(null, -1, 0); // write first chunk message id msgId.setFirstChunkMessageId(); firstChunkMsgId.writeMessageIdData(msgId.getFirstChunkMessageId(), -1, 0); ...
@Test public void serializeAndDeserializeTest() throws IOException { ChunkMessageIdImpl chunkMessageId = new ChunkMessageIdImpl( new MessageIdImpl(0, 0, 0), new MessageIdImpl(1, 1, 1) ); byte[] serialized = chunkMessageId.toByteArray(); ChunkMessageIdI...
@Override void decode(ByteBufAllocator alloc, ByteBuf headerBlock, SpdyHeadersFrame frame) throws Exception { ObjectUtil.checkNotNull(headerBlock, "headerBlock"); ObjectUtil.checkNotNull(frame, "frame"); if (cumulation == null) { decodeHeaderBlock(headerBlock, frame); ...
@Test public void testIllegalValueEndsWithNull() throws Exception { ByteBuf headerBlock = Unpooled.buffer(22); headerBlock.writeInt(1); headerBlock.writeInt(4); headerBlock.writeBytes(nameBytes); headerBlock.writeInt(6); headerBlock.writeBytes(valueBytes); hea...
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void streamStreamLeftJoinTopologyWithCustomStoresNames() { final StreamsBuilder builder = new StreamsBuilder(); final KStream<Integer, String> stream1; final KStream<Integer, String> stream2; stream1 = builder.stream("input-topic1"); stream2 = builder.stream("i...
@Override public MutableTreeRootHolder setRoots(Component root, Component reportRoot) { checkState(this.root == null, "root can not be set twice in holder"); this.root = requireNonNull(root, "root can not be null"); this.extendedTreeRoot = requireNonNull(reportRoot, "extended tree root can not be null"); ...
@Test public void setRoot_throws_ISE_when_called_twice() { underTest.setRoots(DUMB_PROJECT, DUMB_PROJECT); assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) .isInstanceOf(IllegalStateException.class) .hasMessage("root can not be set twice in holder"); }
public void go(PrintStream out) { KieServices ks = KieServices.Factory.get(); KieRepository kr = ks.getRepository(); KieModule kModule = kr.addKieModule(ks.getResources().newFileSystemResource(getFile("default-kiesession"))); KieContainer kContainer = ks.newKieContainer(kModule.getRele...
@Test public void testGo() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); new DefaultKieSessionFromFileExample().go(ps); ps.close(); String actual = baos.toString(); String expected = "" + ...
Set<String> getTargetImageAdditionalTags() { String property = getProperty(PropertyNames.TO_TAGS); List<String> tags = property != null ? ConfigurationPropertyValidator.parseListProperty(property) : to.tags; if (tags.stream().anyMatch(Strings::isNullOrEmpty)) { String source = property != null...
@Test public void testEmptyOrNullTags() { // https://github.com/GoogleContainerTools/jib/issues/1534 // Maven turns empty tags into null entries, and its possible to have empty tags in jib.to.tags sessionProperties.put("jib.to.tags", "a,,b"); Exception ex = assertThrows( IllegalArg...
public void setCompostState(FarmingPatch fp, CompostState state) { log.debug("Storing compost state [{}] for patch [{}]", state, fp); if (state == null) { configManager.unsetRSProfileConfiguration(TimeTrackingConfig.CONFIG_GROUP, configKey(fp)); } else { configManager.setRSProfileConfiguration(TimeTr...
@Test public void setCompostState_storesNonNullChangesToConfig() { compostTracker.setCompostState(farmingPatch, CompostState.COMPOST); verify(configManager).setRSProfileConfiguration("timetracking", "MOCK.compost", CompostState.COMPOST); }
@Override public Object convert(String value) { if (isNullOrEmpty(value)) { return value; } if (value.contains("=")) { final Map<String, String> fields = new HashMap<>(); Matcher m = PATTERN.matcher(value); while (m.find()) { ...
@Test public void testFilterWithWhitespaceAroundKVNoException() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("k1 = "); assertEquals(0, result.size()); }
public static void checkArgument(boolean expression, Object errorMessage) { if (Objects.isNull(errorMessage)) { throw new IllegalArgumentException("errorMessage cannot be null."); } if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); ...
@Test void testCheckArgument2Args1false() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG); }); }
public void validate(ExternalIssueReport report, Path reportPath) { if (report.rules != null && report.issues != null) { Set<String> ruleIds = validateRules(report.rules, reportPath); validateIssuesCctFormat(report.issues, ruleIds, reportPath); } else if (report.rules == null && report.issues != nul...
@Test public void validate_whenDeprecatedReportMissingType_shouldThrowException() throws IOException { ExternalIssueReport report = read(DEPRECATED_REPORTS_LOCATION); report.issues[0].type = null; assertThatThrownBy(() -> validator.validate(report, reportPath)) .isInstanceOf(IllegalStateException.c...
@Override public Object evaluate(final ProcessingDTO processingDTO) { Number input = (Number) getFromPossibleSources(name, processingDTO) .orElse(mapMissingTo); if (input == null) { throw new KiePMMLException("Failed to retrieve input number for " + name); } ...
@Test void evaluateInputAndLimitLinearNorms() { double startOrig = 2.1; double startNorm = 2.6; double endOrig = 7.4; double endNorm = 6.9; KiePMMLLinearNorm startLinearNorm = new KiePMMLLinearNorm("start", Col...
public String toString(SqlFunctionProperties properties) { StringBuilder buffer = new StringBuilder(); if (isSingleValue()) { buffer.append('['); appendQuotedValue(buffer, low, properties); buffer.append(']'); } else { buffer.append((lo...
@Test public void testToString() { Range range = Range.all(VARCHAR); assertEquals(range.toString(PROPERTIES), "(<min>, <max>)"); range = Range.equal(VARCHAR, utf8Slice("some string")); assertEquals(range.toString(PROPERTIES), "[\"some string\"]"); range = Range.equal(VA...
@Override public boolean supportsPluginSettingsNotification() { return false; }
@Test public void shouldNotSupportSettingsNotification() throws Exception { assertFalse(messageHandler.supportsPluginSettingsNotification()); }
@PostMapping("/token") @PermitAll @Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用") @Parameters({ @Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"), @Parameter(name = "code", description = "授权...
@Test public void testPostAccessToken_refreshToken() { // 准备参数 String granType = OAuth2GrantTypeEnum.REFRESH_TOKEN.getGrantType(); String refreshToken = randomString(); String password = randomString(); HttpServletRequest request = mockRequest("test_client_id", "test_client_s...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { this.trash(files, prompt, callback); for(Path f : files.keySet()) { fileid.cache(f, null); } }
@Test public void testDeleteRecursively() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path folder = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)); final Path file = new Path(folder, new ...
@Udf public <T> List<T> distinct( @UdfParameter(description = "Array of values to distinct") final List<T> input) { if (input == null) { return null; } final Set<T> distinctVals = Sets.newLinkedHashSetWithExpectedSize(input.size()); distinctVals.addAll(input); return new ArrayList<>(di...
@Test public void shouldDistinctIntArray() { final List<Integer> result = udf.distinct(Arrays.asList(1, 2, 3, 2, 1)); assertThat(result, contains(1, 2, 3)); }
@Transactional(readOnly = true) public AuthFindDto.FindUsernameRes findUsername(String phone) { User user = readGeneralSignUpUser(phone); return AuthFindDto.FindUsernameRes.of(user); }
@DisplayName("휴대폰 번호로 유저를 찾을 수 없을 때 AuthFinderException을 발생시킨다.") @Test void findUsernameIfUserNotFound() { // given String phone = "010-1234-5678"; given(userService.readUserByPhone(phone)).willReturn(Optional.empty()); // when - then UserErrorException exception = asse...
public static Builder builder() { return new Builder(); }
@Test void testPrimaryKeyGeneratedColumn() { assertThatThrownBy( () -> TableSchema.builder() .field("f0", DataTypes.BIGINT().notNull(), "123") .primaryKey("pk", new String[...
@VisibleForTesting void cleanup(ConnectionPool pool) { if (pool.getNumConnections() > pool.getMinSize()) { // Check if the pool hasn't been active in a while or not 50% are used long timeSinceLastActive = Time.now() - pool.getLastActiveTime(); int total = pool.getNumConnections(); // Activ...
@Test public void testCleanup() throws Exception { Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools(); ConnectionPool pool1 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool1, 9, 4); poolMap.put( ...
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldHaveCleanupPolicyCompactCtas() { // Given: givenStatement("CREATE TABLE x AS SELECT * FROM SOURCE;"); // When: final CreateAsSelect ctas = ((CreateAsSelect) injector.inject(statement, builder).getStatement()); // Then: final CreateSourceAsProperties props = ctas.getPr...
@Override public void onClose(int code, String reason, boolean remote) { log.debug( "Closed WebSocket connection to {}, because of reason: '{}'." + "Connection closed remotely: {}", uri, reason, remote); listener...
@Test public void testNotifyListenerOnClose() throws Exception { client.onClose(1, "reason", true); verify(listener).onClose(); }
void add(StorageType[] storageTypes, BlockStoragePolicy policy) { StorageTypeAllocation storageCombo = new StorageTypeAllocation(storageTypes, policy); Long count = storageComboCounts.get(storageCombo); if (count == null) { storageComboCounts.put(storageCombo, 1l); storageCombo.setActua...
@Test public void testMultipleHots() { BlockStoragePolicySuite bsps = BlockStoragePolicySuite.createDefaultSuite(); StoragePolicySummary sts = new StoragePolicySummary(bsps.getAllPolicies()); BlockStoragePolicy hot = bsps.getPolicy("HOT"); sts.add(new StorageType[]{StorageType.DISK},hot); sts.add(...
@Override public String getHeader(String name) { return stream.response().getHeader(name); }
@Test public void get_header() { underTest.getHeader("header"); verify(response).getHeader("header"); }
@Override protected Result[] run(String value) { final Map<String, Object> extractedJson; try { extractedJson = extractJson(value); } catch (IOException e) { throw new ExtractorException(e); } final List<Result> results = new ArrayList<>(extractedJson....
@Test public void testRunWithFlattenedObject() throws Exception { final JsonExtractor jsonExtractor = new JsonExtractor(new MetricRegistry(), "json", "title", 0L, Extractor.CursorStrategy.COPY, "source", "target", ImmutableMap.<String, Object>of("flatten", true), "user", Collections.<Convert...
public void pruneColumns(Configuration conf, Path inputFile, Path outputFile, List<String> cols) throws IOException { RewriteOptions options = new RewriteOptions.Builder(conf, inputFile, outputFile) .prune(cols) .build(); ParquetRewriter rewriter = new ParquetRewriter(options); rewrite...
@Test public void testNotExistsNestedColumn() throws Exception { // Create Parquet file String inputFile = createParquetFile("input"); String outputFile = createTempFile("output"); List<String> cols = Arrays.asList("Links.Not_exists"); columnPruner.pruneColumns(conf, new Path(inputFile), new Path(...
public GrantDTO create(GrantDTO grantDTO, @Nullable User currentUser) { return create(grantDTO, requireNonNull(currentUser, "currentUser cannot be null").getName()); }
@Test public void createWithGrantDTOAndUsernameString() { final GRN grantee = GRNTypes.USER.toGRN("jane"); final GRN target = GRNTypes.DASHBOARD.toGRN("54e3deadbeefdeadbeef0000"); final GrantDTO grant = dbService.create(GrantDTO.of(grantee, Capability.MANAGE, target), "admin"); ass...
@VisibleForTesting static boolean atMostOne(boolean... values) { boolean one = false; for (boolean value : values) { if (!one && value) { one = true; } else if (value) { return false; } } return true; }
@Test public void testAtMostOne() { assertTrue(atMostOne(true)); assertTrue(atMostOne(false)); assertFalse(atMostOne(true, true)); assertTrue(atMostOne(true, false)); assertTrue(atMostOne(false, true)); assertTrue(atMostOne(false, false)); assertFalse(atMostOne(true, true, true)); asse...
@Override public void start() { DatabaseCharsetChecker.State state = DatabaseCharsetChecker.State.STARTUP; if (upgradeStatus.isUpgraded()) { state = DatabaseCharsetChecker.State.UPGRADE; } else if (upgradeStatus.isFreshInstall()) { state = DatabaseCharsetChecker.State.FRESH_INSTALL; } ...
@Test public void test_fresh_install() { when(upgradeStatus.isFreshInstall()).thenReturn(true); underTest.start(); verify(charsetChecker).check(DatabaseCharsetChecker.State.FRESH_INSTALL); }
@Override public long freeze() { finalizeSnapshotWithFooter(); appendBatches(accumulator.drain()); snapshot.freeze(); accumulator.close(); return snapshot.sizeInBytes(); }
@Test void testBuilderKRaftVersion0() { OffsetAndEpoch snapshotId = new OffsetAndEpoch(100, 10); int maxBatchSize = 1024; AtomicReference<ByteBuffer> buffer = new AtomicReference<>(null); RecordsSnapshotWriter.Builder builder = new RecordsSnapshotWriter.Builder() .setKraf...
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) { if ( lists == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "lists", "cannot be null")); } final Set<Object> resultSet = new LinkedHashSet<>(); for ( final Obj...
@Test void invokeListAndSingleObject() { FunctionTestUtil.assertResultList(unionFunction.invoke(new Object[]{Arrays.asList(10, 4, 5), 1}), Arrays.asList(10, 4, 5, 1)); }
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowDbPriv() throws AnalysisException, DdlException { ShowDbStmt stmt = new ShowDbStmt(null); ctx.setGlobalStateMgr(AccessTestUtil.fetchBlockCatalog()); ctx.setCurrentUserIdentity(UserIdentity.ROOT); ShowResultSet resultSet = ShowExecutor.execute(stmt, ctx); ...
public static InternalLogger getInstance(Class<?> clazz) { return getInstance(clazz.getName()); }
@Test public void testDebugWithException() { final InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.debug("a", e); verify(mockLogger).debug("a", e); }
public void init(final InternalProcessorContext<KOut, VOut> context) { if (!closed) throw new IllegalStateException("The processor is not closed"); try { threadId = Thread.currentThread().getName(); internalProcessorContext = context; droppedRecordsSensor...
@Test public void shouldThrowStreamsExceptionIfExceptionCaughtDuringInit() { final ProcessorNode<Object, Object, Object, Object> node = new ProcessorNode<>(NAME, new ExceptionalProcessor(), Collections.emptySet()); assertThrows(StreamsException.class, () -> node.init(null)); }
public List<Shard> listShardsFollowingClosedShard( final String streamName, final String exclusiveStartShardId) throws TransientKinesisException { ShardFilter shardFilter = ShardFilter.builder() .type(ShardFilterType.AFTER_SHARD_ID) .shardId(exclusiveStartShardId) ...
@Test public void shouldListAllShardsForExclusiveStartShardId() throws Exception { Shard shard1 = Shard.builder().shardId(SHARD_1).build(); Shard shard2 = Shard.builder().shardId(SHARD_2).build(); Shard shard3 = Shard.builder().shardId(SHARD_3).build(); String exclusiveStartShardId = "exclusiveStartS...
public void commitVersions() { this.jobVersioners.forEach(JobVersioner::commitVersion); }
@Test void testJobListVersionerOnCommitVersionIsIncreased() { // GIVEN Job job1 = aScheduledJob().withVersion(5).build(); Job job2 = aScheduledJob().withVersion(5).build(); // WHEN JobListVersioner jobListVersioner = new JobListVersioner(asList(job1, job2)); jobListV...
public static Write write() { return new AutoValue_RedisIO_Write.Builder() .setConnectionConfiguration(RedisConnectionConfiguration.create()) .setMethod(Write.Method.APPEND) .build(); }
@Test public void testWriteWithMethodPFAdd() { String key = "testWriteWithMethodPFAdd"; List<String> values = Arrays.asList("0", "1", "2", "3", "2", "4", "0", "5"); List<KV<String, String>> data = buildConstantKeyList(key, values); PCollection<KV<String, String>> write = p.apply(Create.of(data)); ...
@Override public void archiveCompletedReservations(long tick) { // Since we are looking for old reservations, read lock is optimal LOG.debug("Running archival at time: {}", tick); List<InMemoryReservationAllocation> expiredReservations = new ArrayList<InMemoryReservationAllocation>(); readLock...
@Test public void testArchiveCompletedReservations() { SharingPolicy sharingPolicy = mock(SharingPolicy.class); Plan plan = new InMemoryPlan(queueMetrics, sharingPolicy, agent, totalCapacity, 1L, resCalc, minAlloc, maxAlloc, planName, replanner, true, context); ReservationId reservatio...
@Beta public static Application fromBuilder(Builder builder) throws Exception { return builder.build(); }
@Test void application_generation_metric() throws Exception { try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container() ...
public static CustomWeighting.Parameters createWeightingParameters(CustomModel customModel, EncodedValueLookup lookup) { String key = customModel.toString(); Class<?> clazz = customModel.isInternal() ? INTERNAL_CACHE.get(key) : null; if (CACHE_SIZE > 0 && clazz == null) clazz = CACHE...
@Test void testPriority() { EdgeIteratorState primary = graph.edge(0, 1).setDistance(10). set(roadClassEnc, PRIMARY).set(avgSpeedEnc, 80).set(accessEnc, true, true); EdgeIteratorState secondary = graph.edge(1, 2).setDistance(10). set(roadClassEnc, SECONDARY).set(avgSp...
@Override public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException { return new Checksum(HashAlgorithm.md5, this.digest("MD5", this.normalize(in, status), status)); }
@Test public void testCompute() throws Exception { assertEquals("a43c1b0aa53a0c908810c06ab1ff3967", new MD5ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()), new TransferStatus()).hash); }
public void validate(ProjectReactor reactor) { List<String> validationMessages = new ArrayList<>(); for (ProjectDefinition moduleDef : reactor.getProjects()) { validateModule(moduleDef, validationMessages); } if (isBranchFeatureAvailable()) { branchParamsValidator.validate(validationMessag...
@Test void fail_when_backslash_in_key() { ProjectReactor reactor = createProjectReactor("foo\\bar"); assertThatThrownBy(() -> underTest.validate(reactor)) .isInstanceOf(MessageException.class) .hasMessageContaining("\"foo\\bar\" is not a valid project key. Allowed characters are alphanumeric, " ...
@Override public void commitJob(JobContext jobContext) throws IOException { Configuration conf = jobContext.getConfiguration(); syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false); overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false); updateRoot = c...
@Test public void testNoCommitAction() throws IOException { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl( taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); OutputCommitter committer...
public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry>...
@Test public void testFilterAclEntriesByAclSpecAutomaticDefaultOther() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT...
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) { list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file)); } ...
@Test public void testProviderUriWithKey() { final Iterator<DescriptiveUrl> provider = new S3UrlProvider(session, Collections.emptyMap()).toUrl(new Path("/test-eu-west-1-cyberduck/key", EnumSet.of(Path.Type.file))).filter(DescriptiveUrl.Type.provider).iterator(); assertEquals("s3://t...
public ServiceBusConfiguration getConfiguration() { return configuration; }
@Test void testCreateEndpointWithConfig() throws Exception { final String uri = "azure-servicebus://testTopicOrQueue"; final String remaining = "testTopicOrQueue"; final Map<String, Object> params = new HashMap<>(); params.put("serviceBusType", ServiceBusType.topic); params.p...
public PackageRepository findPackageRepositoryHaving(String packageId) { for (PackageRepository packageRepository : this) { for (PackageDefinition packageDefinition : packageRepository.getPackages()) { if (packageDefinition.getId().equals(packageId)) { return pack...
@Test void shouldReturnNullWhenRepositoryForGivenPackageNotFound() throws Exception { PackageRepositories packageRepositories = new PackageRepositories(); assertThat(packageRepositories.findPackageRepositoryHaving("invalid")).isNull(); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { boolean forceRedirect = config .getBoolean(SONAR_FORCE_REDIRECT_DEFAULT_ADMIN_CREDENTIALS) .orElse(true); if (forceRedirect && userSession.hasSession() && userSession.isLoggedIn() ...
@Test public void do_not_redirect_if_config_says_so() throws Exception { when(config.getBoolean("sonar.forceRedirectOnDefaultAdminCredentials")).thenReturn(Optional.of(false)); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); }
@Override public Thread newThread(Runnable r) { Thread t = newThread(FastThreadLocalRunnable.wrap(r), prefix + nextId.incrementAndGet()); try { if (t.isDaemon() != daemon) { t.setDaemon(daemon); } if (t.getPriority() != priority) { ...
@Test @Timeout(value = 2000, unit = TimeUnit.MILLISECONDS) public void testCurrentThreadGroupIsUsed() throws InterruptedException { final AtomicReference<DefaultThreadFactory> factory = new AtomicReference<DefaultThreadFactory>(); final AtomicReference<ThreadGroup> firstCaptured = new AtomicRefe...
public static long hash(Slice decimal) { return hash(getRawLong(decimal, 0), getRawLong(decimal, 1)); }
@Test public void testHash() { assertEquals(hash(unscaledDecimal(0)), hash(negate(unscaledDecimal(0)))); assertNotEquals(hash(unscaledDecimal(0)), hash(unscaledDecimal(1))); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindVarargsOne() { // Given: givenFunctions( function(EXPECTED, 0, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING))); // Then: assertThat(fun.name(), equalTo(EXPECTED)); }