focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Write write() { return new Write(null /* Configuration */, ""); }
@Test public void testWriteValidationFailsMissingTable() { HBaseIO.Write write = HBaseIO.write().withConfiguration(conf); thrown.expect(IllegalArgumentException.class); write.expand(null /* input */); }
@Private public void handleEvent(JobHistoryEvent event) { synchronized (lock) { // If this is JobSubmitted Event, setup the writer if (event.getHistoryEvent().getEventType() == EventType.AM_STARTED) { try { AMStartedEvent amStartedEvent = (AMStartedEvent) event.getHist...
@Test (timeout=50000) public void testMaxUnflushedCompletionEvents() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.workDir); conf.setLong(MRJobConfig.MR_AM_HISTORY_COMPLETE_EVENT_FLUSH_TIMEOUT_MS, 60 * 10...
@Override public ObjectNode encode(Intent intent, CodecContext context) { checkNotNull(intent, "Intent cannot be null"); final ObjectNode result = context.mapper().createObjectNode() .put(TYPE, intent.getClass().getSimpleName()) .put(ID, intent.id().toString()) ...
@Test public void intentWithTreatmentSelectorAndConstraints() { ConnectPoint ingress = NetTestTools.connectPoint("ingress", 1); ConnectPoint egress = NetTestTools.connectPoint("egress", 2); DeviceId did1 = did("device1"); DeviceId did2 = did("device2"); DeviceId did3 = did("d...
public static <C> AsyncBuilder<C> builder() { return new AsyncBuilder<>(); }
@SuppressWarnings("deprecation") @Test void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { Map<String, Collection<String>> headers = new LinkedHashMap<>(); headers.put("Location", Arrays.asList("http://bar.com")); final Response response = Response.builder().status(302).reason("Found").hea...
@Override public void put(V e) throws InterruptedException { RedissonQueueSemaphore semaphore = createSemaphore(e); semaphore.acquire(); }
@Test public void testPut() throws InterruptedException { final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("bounded-queue"); queue1.trySetCapacity(3); queue1.add(1); queue1.add(2); queue1.add(3); ScheduledExecutorService executor...
@Override public ExecuteContext after(ExecuteContext context) { if (handler != null) { handler.doAfter(context); return context; } DefaultLitePullConsumerWrapper wrapper = RocketMqPullConsumerController .getPullConsumerWrapper((DefaultLitePullConsumer...
@Test public void testAfter() { subscription.remove("test-topic"); interceptor.after(context); Assert.assertEquals(pullConsumerWrapper.getSubscribedTopics().size(), 0); }
@Override public int getRowCount() { return _groupByResults.size(); }
@Test public void testGetRowCount() { // Run the test final int result = _groupByResultSetUnderTest.getRowCount(); // Verify the results assertEquals(2, result); }
@Override public boolean isShutdown() { return delegate.isShutdown(); }
@Test public void isShutdown_delegates_to_executorService() { underTest.isShutdown(); inOrder.verify(executorService).isShutdown(); inOrder.verifyNoMoreInteractions(); }
public Map<String, String> getAllProperties() { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); return builder.put(CONCURRENT_LIFESPANS_PER_TASK, String.valueOf(getConcurrentLifespansPerTask())) .put(ENABLE_SERIALIZED_PAGE_CHECKSUM, String.valueOf(isEnableSeria...
@Test public void testNativeExecutionNodeConfig() { // Test defaults assertRecordedDefaults(ConfigAssertions.recordDefaults(NativeExecutionNodeConfig.class) .setNodeEnvironment("spark-velox") .setNodeLocation("/dummy/location") .setNodeInternalAddr...
public static FileRewriteCoordinator get() { return INSTANCE; }
@Test public void testBinPackRewrite() throws NoSuchTableException, IOException { sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName); Dataset<Row> df = newDF(1000); df.coalesce(1).writeTo(tableName).append(); df.coalesce(1).writeTo(tableName).append(); df.coalesce(1).writeTo(ta...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void createSetAndAddStickerTgs() { String setName = "test" + System.currentTimeMillis() + "_by_pengrad_test_bot"; InputSticker[] stickers = new InputSticker[]{new InputSticker(stickerFileAnim, Sticker.Format.animated, new String[]{"\uD83D\uDE00"})}; BaseResponse response = bot.e...
@VisibleForTesting static void configureSslEngineFactory( final KsqlConfig config, final SslEngineFactory sslFactory ) { sslFactory .configure(config.valuesWithPrefixOverride(KsqlConfig.KSQL_SCHEMA_REGISTRY_PREFIX)); }
@Test public void shouldPickUpNonPrefixedSslConfig() { // Given: final KsqlConfig config = config( SslConfigs.SSL_PROTOCOL_CONFIG, "SSLv3" ); final Map<String, Object> expectedConfigs = defaultConfigs(); expectedConfigs.put(SslConfigs.SSL_PROTOCOL_CONFIG, "SSLv3"); // When: KsqlS...
@Override public int indexOfValue( String valueName ) { if ( valueName == null ) { return -1; } lock.writeLock().lock(); try { Integer index = cache.findAndCompare( valueName, valueMetaList ); for ( int i = 0; ( index == null ) && ( i < valueMetaList.size() ); i++ ) { if ( v...
@Test public void testIndexOfValue() { List<ValueMetaInterface> list = rowMeta.getValueMetaList(); assertEquals( 0, list.indexOf( string ) ); assertEquals( 1, list.indexOf( integer ) ); assertEquals( 2, list.indexOf( date ) ); }
public static boolean shouldLoadInIsolation(String name) { return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches()); }
@Test public void testAllowedBasicAuthExtensionClasses() { List<String> basicAuthExtensionClasses = Arrays.asList( "org.apache.kafka.connect.rest.basic.auth.extension.BasicAuthSecurityRestExtension" //"org.apache.kafka.connect.rest.basic.auth.extension.JaasBasicAuthFilter", TODO fix?...
public boolean isAvailable(String featureName) { String name = FEATURE_PREFIX + featureName; String sysprop = System.getProperty(name); if (sysprop != null) { return Boolean.parseBoolean(sysprop); } else { return Boolean.parseBoolean(features.getProperty(name, "true")); }...
@Test public void featureSysOverride() { Features features = new Features(); assertFalse(features.isAvailable("A")); System.setProperty("org.infinispan.feature.A", "true"); System.setProperty("org.infinispan.feature.B", "false"); boolean a = features.isAvailable("A"); boolean b = ...
public static long toMillis(long day, long hour, long minute, long second, long millis) { try { long value = millis; value = addExact(value, multiplyExact(day, MILLIS_IN_DAY)); value = addExact(value, multiplyExact(hour, MILLIS_IN_HOUR)); value = addExact(valu...
@Test(expectedExceptions = IllegalArgumentException.class) public void testOverflow() { long days = (Long.MAX_VALUE / DAYS.toMillis(1)) + 1; toMillis(days, 0, 0, 0, 0); }
public long timeout() { if (tickets.isEmpty()) { return -1; } sortIfNeeded(); // Tickets are sorted, so check first ticket Ticket first = tickets.get(0); long time = first.start - now() + first.delay; if (time > 0) { return time; ...
@Test public void testNoTicket() { assertThat(tickets.timeout(), is(-1L)); }
@Override @SuppressWarnings("MissingDefault") public boolean offer(final E e) { if (e == null) { throw new NullPointerException(); } long mask; E[] buffer; long pIndex; while (true) { long producerLimit = lvProducerLimit(); pIndex = lvProducerIndex(this); // lower b...
@Test(dataProvider = "empty") public void manyProducers_noConsumer(MpscGrowableArrayQueue<Integer> queue) { var count = new AtomicInteger(); ConcurrentTestHarness.timeTasks(NUM_PRODUCERS, () -> { for (int i = 0; i < PRODUCE; i++) { if (queue.offer(i)) { count.incrementAndGet(); ...
@Override public VectorIndexConfig setName(String name) { validateName(name); this.indexName = name; return this; }
@Test public void constructorNameValidation_failed() { assertThatThrownBy(() -> new VectorIndexConfig().setName("asd*%6(&")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The name of the vector index should " + "only consist of letters, nu...
public Result toResult(String responseBody) { try { Result result = new Result(); Map<String, Object> map; try { map = GSON.fromJson(responseBody, new TypeToken<Map<String, Object>>() {}.getType()); } catch (Exception e) { throw ne...
@Test public void shouldBuildFailureResultFromResponseBody() { String responseBody = "{\"status\":\"failure\",messages=[\"message-one\",\"message-two\"]}"; Result result = messageHandler.toResult(responseBody); assertFailureResult(result, List.of("message-one", "message-two")); }
@Override public OptionalLong apply(OptionalLong previousSendTimeNs) { long delayNs; if (previousGlobalFailures > 0) { // If there were global failures (like a response timeout), we want to wait for the // full backoff period. delayNs = backoff.backoff(previousGlo...
@Test public void applyAfterDispatchInterval() { assertEquals(OptionalLong.of(BACKOFF.initialInterval()), new AssignmentsManagerDeadlineFunction(BACKOFF, 0, 0, false, 12). apply(OptionalLong.empty())); }
@InvokeOnHeader(Web3jConstants.ETH_COMPILE_LLL) void ethCompileLLL(Message message) throws IOException { String sourceCode = message.getHeader(Web3jConstants.SOURCE_CODE, configuration::getSourceCode, String.class); Request<?, EthCompileLLL> request = web3j.ethCompileLLL(sourceCode); setRequ...
@Test public void ethCompileLLLTest() throws Exception { EthCompileLLL response = Mockito.mock(EthCompileLLL.class); Mockito.when(mockWeb3j.ethCompileLLL(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getCompiledSourceCode()).the...
@Override public boolean match(String attributeValue) { if (attributeValue == null) { return false; } switch (type) { case Equals: return attributeValue.equals(value); case StartsWith: return (length == -1 || length == attributeValue.length()) && ...
@Test public void testDegeneratedStartsWith() { assertTrue(new LikeCondition("ab%").match("ab")); assertTrue(new LikeCondition("ab%").match("abx")); assertTrue(new LikeCondition("ab%").match("abxx")); assertFalse(new LikeCondition("ab%").match("xab")); assertFalse(new LikeCondition("ab%...
@Override public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment, InstancePartitions instancePartitions, InstancePartitionsType instancePartitionsType) { validateSegmentAssignmentStrategy(instancePartitions); return SegmentAssignmentUtils.assignSegmentWi...
@Test public void testBootstrapTable() { Map<String, Map<String, String>> currentAssignment = new TreeMap<>(); for (String segmentName : SEGMENTS) { List<String> instancesAssigned = _segmentAssignment.assignSegment(segmentName, currentAssignment, _instancePartitionsMap); currentAssignmen...
@Override public ObjectNode encode(MastershipRole mastershipRole, CodecContext context) { checkNotNull(mastershipRole, "MastershipRole cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(ROLE, mastershipRole.name()); return result; }
@Test public void testMastershipRoleEncode() { MastershipRole mastershipRole = MASTER; ObjectNode mastershipRoleJson = mastershipRoleCodec.encode(mastershipRole, context); assertThat(mastershipRoleJson, MastershipRoleJsonMatcher.matchesMastershipRole(mastershipRole)); }
public static Builder withMaximumSizeBytes(long maxBloomFilterSizeBytes) { checkArgument(maxBloomFilterSizeBytes > 0, "Expected Bloom filter size limit to be positive."); long optimalNumberOfElements = optimalNumInsertions(maxBloomFilterSizeBytes, DEFAULT_FALSE_POSITIVE_PROBABILITY); checkArgument( ...
@Test public void testBuilder() throws Exception { ScalableBloomFilter.Builder builder = ScalableBloomFilter.withMaximumSizeBytes(MAX_SIZE); assertTrue("Expected Bloom filter to have been modified.", builder.put(BUFFER)); // Re-adding should skip and not record the insertion. assertFalse("Expected Bl...
public static void trackGeTuiNotificationClicked(String title, String content, String sfData, long time) { trackNotificationOpenedEvent(sfData, title, content, "GeTui", null, time); }
@Test public void trackGeTuiNotificationClicked() { SensorsDataAPI sensorsDataAPI = SAHelper.initSensors(mApplication); final CountDownLatch countDownLatch = new CountDownLatch(1); sensorsDataAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override pu...
@Override public String toString() { return getClass().getSimpleName() + " barCount: " + barCount; }
@Test public void naNValuesInInterval() { BaseBarSeries series = new BaseBarSeries("NaN test"); for (long i = 0; i <= 10; i++) { // (0, NaN, 2, NaN, 4, NaN, 6, NaN, 8, ...) Num highPrice = i % 2 == 0 ? series.numOf(i) : NaN; series.addBar(ZonedDateTime.now().plusDays(i), NaN,...
public static byte[] getMCastMacAddress(byte[] targetIp) { checkArgument(targetIp.length == Ip6Address.BYTE_LENGTH); return new byte[] { 0x33, 0x33, targetIp[targetIp.length - 4], targetIp[targetIp.length - 3], targetIp[targetIp.length - 2]...
@Test public void testMulticastAddress() { assertArrayEquals(MULTICAST_ADDRESS, getMCastMacAddress(DESTINATION_ADDRESS)); }
public static COSNumber get( String number ) throws IOException { if (number.length() == 1) { char digit = number.charAt(0); if ('0' <= digit && digit <= '9') { return COSInteger.get((long) digit - '0'); } if (digit == '-'...
@Test void testInvalidNumber() { try { COSNumber.get("18446744073307F448448"); fail("Was expecting an IOException"); } catch (IOException e) { } }
@SuppressWarnings("unchecked") @Override public Result execute(Query query, Target target) { Query adjustedQuery = adjustQuery(query); switch (target.mode()) { case ALL_NODES: adjustedQuery = Query.of(adjustedQuery).partitionIdSet(getAllPartitionIds()).build(); ...
@Test public void runQueryOnLocalPartitions() { Predicate<Object, Object> predicate = Predicates.equal("this", value); Query query = Query.of().mapName(map.getName()).predicate(predicate).iterationType(KEY).build(); QueryResult result = queryEngine.execute(query, Target.LOCAL_NODE); ...
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { try { if (statement.getStatement() instanceof CreateAsSelect) { registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement); ...
@Test public void shouldThrowInconsistentSchemaIdExceptionWithOverrideSchema() throws IOException, RestClientException { // Given: when(schemaRegistryClient.register(anyString(), any(ParsedSchema.class))).thenReturn(2); final SchemaAndId schemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), AVRO_SCH...
@Nullable @Override protected SelectionResultsBlock getNextBlock() { if (_numDocsScanned >= _limit) { // Already returned enough documents return null; } ValueBlock valueBlock = _projectOperator.nextBlock(); if (valueBlock == null) { return null; } int numExpressions = _exp...
@Test public void testNullHandling() { QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT * FROM testTable WHERE intColumn IS NULL"); queryContext.setNullHandlingEnabled(true); List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(query...
public void run() throws Exception { final Terminal terminal = TerminalBuilder.builder() .nativeSignals(true) .signalHandler(signal -> { if (signal == Terminal.Signal.INT || signal == Terminal.Signal.QUIT) { if (execState == ExecState.R...
@Test public void testInteractiveMode() throws Exception { Terminal terminal = TerminalBuilder.builder().build(); final MockLineReader linereader = new MockLineReader(terminal); final Properties props = new Properties(); props.setProperty("webServiceUrl", "http://localhost:8080"); ...
public void setIgnoreCookies(boolean ignoreCookies) { kp.put("ignoreCookies",ignoreCookies); }
@Test public void testIgnoreCookies() throws Exception { fetcher().setIgnoreCookies(true); checkSetCookieURI(); // second request to see if cookie is NOT sent CrawlURI curi = makeCrawlURI("http://localhost:7777/"); fetcher().process(curi); runDefaultChecks(curi); ...
public static boolean containsSymlink(String path) { return (firstSymlinkIndex(path) < 0) ? false : true; }
@Test public void testContainsSymlink() { Assert.assertTrue(SymlinkUtil.containsSymlink(path1)); Assert.assertTrue(SymlinkUtil.containsSymlink(path2)); Assert.assertTrue(SymlinkUtil.containsSymlink(path3)); Assert.assertFalse(SymlinkUtil.containsSymlink(path4)); Assert.assertFalse(SymlinkUtil.co...
@SuppressWarnings("unchecked") public static <T> TypeInformation<T> convert(String jsonSchema) { Preconditions.checkNotNull(jsonSchema, "JSON schema"); final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper(); mapper.getFactory() .enable(JsonParser.Feature.ALLOW_...
@Test void testAtomicType() { final TypeInformation<?> result = JsonRowSchemaConverter.convert("{ type: 'number' }"); assertThat(result).isEqualTo(Types.BIG_DEC); }
@Deprecated public static String updateSerializedOptions( String serializedOptions, Map<String, String> runtimeValues) { ObjectNode root, options; try { root = PipelineOptionsFactory.MAPPER.readValue(serializedOptions, ObjectNode.class); options = (ObjectNode) root.get("options"); chec...
@Test public void testUpdateSerializeEmptyUpdate() throws Exception { TestOptions submitOptions = PipelineOptionsFactory.as(TestOptions.class); String serializedOptions = MAPPER.writeValueAsString(submitOptions); String updatedOptions = ValueProviders.updateSerializedOptions(serializedOptions, Imm...
@Override public void putByPath(String expression, Object value) { BeanPath.create(expression).set(this, value); }
@Test public void putByPathTest() { final JSONObject json = new JSONObject(); json.putByPath("aa.bb", "BB"); assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString()); }
public static Object get(Object object, int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } if (object instanceof Map) { Map map = (Map) object; Iterator iterator = map.entrySet().iterator(); r...
@Test void testGetIterator3() { assertEquals("1", CollectionUtils.get(Collections.singleton("1").iterator(), 0)); assertEquals("2", CollectionUtils.get(Arrays.asList("1", "2").iterator(), 1)); }
public static <T> AvroCoder<T> reflect(TypeDescriptor<T> type) { return reflect((Class<T>) type.getRawType()); }
@Test public void testAvroReflectCoderIsSerializable() throws Exception { AvroCoder<Pojo> coder = AvroCoder.reflect(Pojo.class); // Check that the coder is serializable using the regular JSON approach. SerializableUtils.ensureSerializable(coder); }
public static byte[] getBytesWithoutClosing(InputStream stream) throws IOException { if (stream instanceof ExposedByteArrayInputStream) { // Fast path for the exposed version. return ((ExposedByteArrayInputStream) stream).readAll(); } else if (stream instanceof ByteArrayInputStream) { // Fast ...
@Test public void testGetBytesFromInputStream() throws IOException { // Any stream which is not a ByteArrayInputStream. InputStream stream = new BufferedInputStream(new ByteArrayInputStream(testData)); byte[] bytes = StreamUtils.getBytesWithoutClosing(stream); assertArrayEquals(testData, bytes); a...
@Override public void serialize(Asn1OutputStream out, Class<? extends ASN1Object> type, ASN1Object obj, Asn1ObjectMapper mapper) throws IOException { out.write(obj.getEncoded()); }
@Test public void shouldSerialize() { assertArrayEquals( new byte[] { 0x13, 03, 'E', 'U', 'R' }, serialize(new Iso4217CurrencyCodeConverter(), Iso4217CurrencyCode.class, new Iso4217CurrencyCode("EUR")) ); }
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException | JMException e) { return null; } }
@Test public void returnsJmxAttribute() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); assertThat(gauge.getValue()).isInstanceOf(Integer.class); a...
@Override public void close() { }
@Test public void shouldSucceed_gapDetectedLocal_disableAlos() throws ExecutionException, InterruptedException { // Given: when(pushRoutingOptions.alosEnabled()).thenReturn(false); final AtomicReference<Set<KsqlNode>> nodes = new AtomicReference<>( ImmutableSet.of(ksqlNodeLocal, ksqlNodeRemo...
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testGetOffsetsIncludesLeaderEpoch() { buildFetcher(); subscriptions.assignFromUser(singleton(tp0)); client.updateMetadata(initialUpdateResponse); // Metadata update with leader epochs MetadataResponse metadataResponse = RequestTestUtils.metadataUpdateWithI...
@Override public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) { // unfortunately, this method does not run in the scheduler executor, but in the // checkpoint coordinator time thread. // we can remove the delegation once the checkpoint coordinator runs full...
@Test void checkpointFutureInitiallyNotDone() throws Exception { final EventReceivingTasks tasks = EventReceivingTasks.createForRunningTasks(); final OperatorCoordinatorHolder holder = createCoordinatorHolder(tasks, TestingOperatorCoordinator::new); final CompletableFuture<b...
public static void checkParam(String dataId, String group, String content) throws NacosException { checkKeyParam(dataId, group); if (StringUtils.isBlank(content)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, CONTENT_INVALID_MSG); } }
@Test void testCheckParam2() throws NacosException { String dataId = "b"; String group = "c"; String datumId = "d"; String content = "a"; ParamUtils.checkParam(dataId, group, datumId, content); }
public NshServicePathId nshSpi() { return nshSpi; }
@Test public void testConstruction() { final NiciraSetNshSpi niciraSetNshSpi = new NiciraSetNshSpi(NshServicePathId.of(10)); assertThat(niciraSetNshSpi, is(notNullValue())); assertThat(niciraSetNshSpi.nshSpi().servicePathId(), is(10)); }
public static MetricsReporter combine(MetricsReporter first, MetricsReporter second) { if (null == first) { return second; } else if (null == second || first == second) { return first; } Set<MetricsReporter> reporters = Sets.newIdentityHashSet(); if (first instanceof CompositeMetricsRe...
@Test public void reportWithMultipleMetricsReporters() { AtomicInteger counter = new AtomicInteger(); MetricsReporter combined = MetricsReporters.combine( report -> counter.incrementAndGet(), report -> counter.incrementAndGet()); combined.report(new MetricsReport() {}); assertTha...
public static Map<String, PluginConfiguration> swap(final YamlAgentConfiguration yamlConfig) { YamlPluginCategoryConfiguration plugins = yamlConfig.getPlugins(); if (null == plugins) { return Collections.emptyMap(); } Map<String, PluginConfiguration> result = new LinkedHashMa...
@Test void assertSwapWithNullPlugins() { YamlAgentConfiguration yamlAgentConfig = new YamlAgentConfiguration(); yamlAgentConfig.setPlugins(new YamlPluginCategoryConfiguration()); assertTrue(YamlPluginsConfigurationSwapper.swap(yamlAgentConfig).isEmpty()); }
public void start() { myBatis.start(); }
@Test void should_start_mybatis_instance() { var myBatis = mock(MyBatis.class); var startMyBatis = new StartMyBatis(myBatis); startMyBatis.start(); verify(myBatis).start(); verifyNoMoreInteractions(myBatis); }
@Override public void doSendMail(MailSendMessage message) { // 1. 创建发送账号 MailAccountDO account = validateMailAccount(message.getAccountId()); MailAccount mailAccount = buildMailAccount(account, message.getNickname()); // 2. 发送邮件 try { String messageId = MailUtil....
@Test public void testDoSendMail_success() { try (MockedStatic<MailUtil> mailUtilMock = mockStatic(MailUtil.class)) { // 准备参数 MailSendMessage message = randomPojo(MailSendMessage.class, o -> o.setNickname("芋艿")); // mock 方法(获得邮箱账号) MailAccountDO account = rand...
public static Container createCategorie(String categorieNummer, String... elementNummerValues) { Container categorie = new Container(); categorie.setNummer(categorieNummer); for(int i = 0 ; i < elementNummerValues.length; i+=2) { Element element = new Element(); element.s...
@Test public void testCreateCategorie() { Container container = CategorieUtil.createCategorie("A", "B", "C", "D", "E"); assertThat(container.getNummer(), is("A")); assertThat(container.getElement().size(), is(2)); assertThat(container.getElement().get(0).getNummer(), is("B")); ...
@Override public void setMaxTimestamp(TimestampType timestampType, long maxTimestamp) { long currentMaxTimestamp = maxTimestamp(); // We don't need to recompute crc if the timestamp is not updated. if (timestampType() == timestampType && currentMaxTimestamp == maxTimestamp) retur...
@Test public void testSetNoTimestampTypeNotAllowed() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, Compression.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b"...
public static String cut(String s, String splitChar, int index) { if (s == null || splitChar == null || index < 0) { return null; } final String[] parts = s.split(Pattern.quote(splitChar)); if (parts.length <= index) { return null; } return empty...
@Test public void testCutReturnsCorrectPart() throws Exception { String result = SplitAndIndexExtractor.cut("foobar foobaz quux", " ", 2); assertEquals("quux", result); }
static <T extends Type> String encodeArrayValues(Array<T> value) { StringBuilder result = new StringBuilder(); for (Type type : value.getValue()) { result.append(encode(type)); } return result.toString(); }
@Test public void testStaticStructStaticArray() { StaticArray3<Bar> array = new StaticArray3<>( Bar.class, new Bar(BigInteger.ONE, BigInteger.ZERO), new Bar(BigInteger.ONE, BigInteger.ZERO), new B...
@Override public ProxyInvocationHandler parserInterfaceToProxy(Object target, String objectName) { // eliminate the bean without two phase annotation. Set<String> methodsToProxy = this.tccProxyTargetMethod(target); if (methodsToProxy.isEmpty()) { return null; } //...
@Test public void testNestTcc_should_rollback() throws Exception { //given RootContext.unbind(); DefaultResourceManager.get(); DefaultResourceManager.mockResourceManager(BranchType.TCC, resourceManager); TransactionManagerHolder.set(transactionManager); TccActionImp...
@Override public synchronized String getUri() { return String.format( "jdbc:%s://%s:%d/%s", getJDBCPrefix(), this.getHost(), this.getPort(), this.getDatabaseName()); }
@Test public void testGetUriShouldReturnCorrectValue() { when(container.getHost()).thenReturn(HOST); when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT); assertThat(testManager.getUri()) .matches("jdbc:" + JDBC_PREFIX + "://" + HOST + ":" + MAPPED_PORT + "/" + DATABASE_NAME); }
@VisibleForTesting DictTypeDO validateDictTypeExists(Long id) { if (id == null) { return null; } DictTypeDO dictType = dictTypeMapper.selectById(id); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); } return dictType; }
@Test public void testValidateDictDataExists_notExists() { assertServiceException(() -> dictTypeService.validateDictTypeExists(randomLongId()), DICT_TYPE_NOT_EXISTS); }
public URLNormalizer encodeNonURICharacters() { url = toURI().toASCIIString(); return this; }
@Test public void testEncodeNonURICharacters() { s = "http://www.example.com/^a [b]/c?d e="; t = "http://www.example.com/%5Ea%20%5Bb%5D/c?d+e="; assertEquals(t, n(s).encodeNonURICharacters().toString()); //Test for https://github.com/Norconex/collector-http/issues/294 //Was ...
public final void contains(@Nullable Object element) { if (!Iterables.contains(checkNotNull(actual), element)) { List<@Nullable Object> elementList = newArrayList(element); if (hasMatchingToStringPair(actual, elementList)) { failWithoutActual( fact("expected to contain", element), ...
@Test public void iterableContains() { assertThat(asList(1, 2, 3)).contains(1); }
@Override public void close() { close(Duration.ofMillis(DEFAULT_CLOSE_TIMEOUT_MS)); }
@Test public void testInterceptorAutoCommitOnClose() { Properties props = requiredConsumerConfigAndGroupId("test-id"); props.setProperty(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, MockConsumerInterceptor.class.getName()); props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true"); ...
PubSubMessage rowToMessage(Row row) { row = castRow(row, row.getSchema(), schema); PubSubMessage.Builder builder = PubSubMessage.newBuilder(); if (schema.hasField(MESSAGE_KEY_FIELD)) { byte[] bytes = row.getBytes(MESSAGE_KEY_FIELD); if (bytes != null) { builder.setKey(ByteString.copyFrom...
@Test public void fullRowToMessage() { RowHandler rowHandler = new RowHandler(FULL_WRITE_SCHEMA); Instant now = Instant.now(); Row row = Row.withSchema(FULL_WRITE_SCHEMA) .withFieldValue(RowHandler.MESSAGE_KEY_FIELD, "val1".getBytes(UTF_8)) .withFieldValue(RowHandler.PAYLOA...
public CompletableFuture<Void> storePqLastResort(final UUID identifier, final byte deviceId, final KEMSignedPreKey lastResortKey) { return pqLastResortKeys.store(identifier, deviceId, lastResortKey); }
@Test void testStorePqLastResort() { assertEquals(0, keysManager.getPqEnabledDevices(ACCOUNT_UUID).join().size()); final ECKeyPair identityKeyPair = Curve.generateKeyPair(); final byte deviceId2 = 2; final byte deviceId3 = 3; keysManager.storePqLastResort(ACCOUNT_UUID, DEVICE_ID, KeysHelper.sig...
@Override public KeyValueIterator<Windowed<K>, V> fetch(final K key) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType); for (final ReadOnlySessionStore<K, V> store : stores) { tr...
@Test public void shouldNotGetValueFromOtherStores() { final Windowed<String> expectedKey = new Windowed<>("foo", new SessionWindow(0, 0)); otherUnderlyingStore.put(new Windowed<>("foo", new SessionWindow(10, 10)), 10L); underlyingSessionStore.put(expectedKey, 1L); try (final KeyVal...
@Override public final Optional<ConfigDefinition> getConfigDefinition(ConfigDefinitionKey defKey) { if (configDefinitionSuppliers == null) { configDefinitionSuppliers = new LinkedHashMap<>(); configDefinitionRepo.ifPresent(definitionRepo -> configDefinitionSuppliers.putAll(createLazy...
@Test void testGetConfigDefinition() { Map<ConfigDefinitionKey, com.yahoo.vespa.config.buildergen.ConfigDefinition> defs = new LinkedHashMap<>(); defs.put(new ConfigDefinitionKey("test2", "a.b"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("test2", new String[]{"namespace=a.b", "doubleVal...
public PrettyTime setLocale(Locale locale) { if (locale == null) locale = Locale.getDefault(); this.locale = locale; for (TimeUnit unit : units.keySet()) { if (unit instanceof LocaleAware) ((LocaleAware<?>) unit).setLocale(locale); } for (TimeFormat format...
@Test public void testSetLocale() throws Exception { PrettyTime t = new PrettyTime(now); final LocalDateTime threeDecadesAgo = now.minus(3, ChronoUnit.DECADES); Assert.assertEquals("3 decades ago", t.format(threeDecadesAgo)); t.setLocale(Locale.GERMAN); Assert.assertEquals("vor 3 Jah...
@Nullable static String getPropertyIfString(Message message, String name) { try { Object o = message.getObjectProperty(name); if (o instanceof String) return o.toString(); return null; } catch (Throwable t) { propagateIfFatal(t); log(t, "error getting property {0} from message {1}"...
@Test void getPropertyIfString_null() { assertThat(MessageProperties.getPropertyIfString(message, "b3")).isNull(); }
public List<Entry> getEntries() { return new ArrayList<>(actions.values()); }
@Test public void actions_with_multiple_services() { List<RefeedActions.Entry> entries = new ConfigChangeActionsBuilder(). refeed(ValidationId.indexModeChange, CHANGE_MSG, DOC_TYPE, CLUSTER, SERVICE_NAME). refeed(ValidationId.indexModeChange, CHANGE_MSG, DOC_TYPE, CLUSTER, SE...
public String encodePassword(String password) throws NoSuchAlgorithmException { // compute digest of the password final MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.update(password.getBytes(StandardCharsets.UTF_8)); // we need a SALT against rainbow tables messageDigest.up...
@Test public void testEncodePassword() throws NoSuchAlgorithmException { final String algorithm = "SHA-256"; final String password = "password"; final String hash = new MessageDigestPasswordEncoder(algorithm).encodePassword(password); final String expectedHash = "{SHA-256}c33d66fe65ffcca1f2260e6982dbf0c614b6ea...
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testVoidResultFunctionDecode() { Function function = new Function("test", Collections.emptyList(), Collections.emptyList()); assertEquals( FunctionReturnDecoder.decode("0x", function.getOutputParameters()), (Collections.emptyList())); }
public static List<FieldSchema> convert(Schema schema) { return schema.columns().stream() .map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc())) .collect(Collectors.toList()); }
@Test public void testNotSupportedTypes() { for (FieldSchema notSupportedField : getNotSupportedFieldSchemas()) { assertThatThrownBy( () -> HiveSchemaUtil.convert( Lists.newArrayList(Collections.singletonList(notSupportedField)))) .isInstanceOf...
@Override public MergeAppend appendFile(DataFile file) { add(file); return this; }
@TestTemplate public void testDefaultPartitionSummaries() { table.newFastAppend().appendFile(FILE_A).commit(); Set<String> partitionSummaryKeys = table.currentSnapshot().summary().keySet().stream() .filter(key -> key.startsWith(SnapshotSummary.CHANGED_PARTITION_PREFIX)) .colle...
public static boolean isConfluentCustomer(final String customerId) { return customerId != null && (CUSTOMER_PATTERN.matcher(customerId.toLowerCase(Locale.ROOT)).matches() || NEW_CUSTOMER_CASE_INSENSISTIVE_PATTERN.matcher(customerId).matches() || NEW_CUSTOMER_CASE_SENSISTIVE_PATTERN.matcher(c...
@Test public void testInvalidCustomer() { String[] invalidIds = Stream.concat( CustomerIdExamples.INVALID_CUSTOMER_IDS.stream(), CustomerIdExamples.VALID_ANONYMOUS_IDS.stream()). toArray(String[]::new); for (String invalidCustomerId : invalidIds) { assertFalse(invalidCustomerId +...
@Override public boolean match(Message msg, StreamRule rule) { if(msg.getField(Message.FIELD_GL2_SOURCE_INPUT) == null) { return rule.getInverted(); } final String value = msg.getField(Message.FIELD_GL2_SOURCE_INPUT).toString(); return rule.getInverted() ^ value.trim().equal...
@Test public void testUnsuccessfulMatchWhenMissing() { StreamRule rule = getSampleRule(); rule.setValue("input-id-dead"); Message msg = getSampleMessage(); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); }
public List<MappingField> resolveAndValidateFields( List<MappingField> userFields, Map<String, String> options, NodeEngine nodeEngine ) { final InternalSerializationService serializationService = (InternalSerializationService) nodeEngine .getSerializationS...
@Test public void when_keyAndValueFieldsEmpty_then_throws() { Map<String, String> options = ImmutableMap.of( OPTION_KEY_FORMAT, JAVA_FORMAT, OPTION_VALUE_FORMAT, JAVA_FORMAT ); given(resolver.resolveAndValidateFields(eq(true), eq(emptyList()), eq(options), eq(...
@Override public SinkRecord newRecord(String topic, Integer kafkaPartition, Schema keySchema, Object key, Schema valueSchema, Object value, Long timestamp, Iterable<Header> headers) { return new InternalSinkRecord(context, topic, kafkaPartition...
@Test public void shouldRetainOriginalTopicPartition() { String transformedTopic = "transformed-test-topic"; SinkRecord sinkRecord = new SinkRecord(transformedTopic, 0, null, null, null, null, 10); ConsumerRecord<byte[], byte[]> consumerRecord = new ConsumerRecord<>(TOPIC, 0, 10, null, null)...
@Override public Mono<Void> withoutFallback(final ServerWebExchange exchange, final Throwable throwable) { Object error; if (throwable instanceof DegradeException) { exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); error = ShenyuResultWrap.error(exchang...
@Test public void testBlockException() { StepVerifier.create(fallbackHandler.withoutFallback(exchange, new AuthorityException("Sentinel"))).expectSubscription().verifyComplete(); }
@Override public Num getValue(int index) { return values.get(index); }
@Test public void cashFlowValueWithNoPositions() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 3d, 2d, 5d, 4d, 7d, 6d, 7d, 8d, 5d, 6d); CashFlow cashFlow = new CashFlow(sampleBarSeries, new BaseTradingRecord()); assertNumEquals(1, cashFlow.getValue(4)); assertNumEquals...
@VisibleForTesting public static String wildcardToRegexp(String globExp) { StringBuilder dst = new StringBuilder(); char[] src = globExp.replace("**/*", "**").toCharArray(); int i = 0; while (i < src.length) { char c = src[i++]; switch (c) { case '*': // One char lookahea...
@Test public void testGlobTranslation() { assertEquals("foo", wildcardToRegexp("foo")); assertEquals("fo[^/]*o", wildcardToRegexp("fo*o")); assertEquals("f[^/]*o\\.[^/]", wildcardToRegexp("f*o.?")); assertEquals("foo-[0-9][^/]*", wildcardToRegexp("foo-[0-9]*")); assertEquals("foo-[0-9].*", wildcar...
public B retries(Integer retries) { this.retries = retries; return getThis(); }
@Test void retries() { MethodBuilder builder = new MethodBuilder(); builder.retries(3); Assertions.assertEquals(3, builder.build().getRetries()); }
public final boolean debug() { return debug(flags); }
@Test void sampled_flags() { assertThat(SamplingFlags.debug(false, SamplingFlags.DEBUG.flags)) .isEqualTo(SamplingFlags.SAMPLED.flags) .isEqualTo(FLAG_SAMPLED_SET | FLAG_SAMPLED); }
public static String idOf(String entityUuid) { requireNonNull(entityUuid, "entityUuid can't be null"); return ID_PREFIX + entityUuid; }
@Test public void idOf_fails_with_NPE_if_argument_is_null() { assertThatThrownBy(() -> AuthorizationDoc.idOf(null)) .isInstanceOf(NullPointerException.class) .hasMessage("entityUuid can't be null"); }
public Set<String> extractPlaceholderKeys(String propertyString) { Set<String> placeholderKeys = Sets.newHashSet(); if (!isPlaceholder(propertyString)) { return placeholderKeys; } Stack<String> stack = new Stack<>(); stack.push(propertyString); while (!stack.isEmpty()) { String strVal = stack.pop()...
@Test public void extractIllegalPlaceholderKeysTest() { final String placeholderCase = "${some.key"; final String placeholderCase1 = "{some.key}"; final String placeholderCase2 = "some.key"; Set<String> placeholderKeys = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase); assertThat(placeholderKeys)...
@Override public void cleanupExpiredSegments(final long streamTime) { super.cleanupExpiredSegments(streamTime); }
@Test public void shouldCleanupSegmentsThatHaveExpired() { final LogicalKeyValueSegment segment1 = segments.getOrCreateSegmentIfLive(0, context, 0); final LogicalKeyValueSegment segment2 = segments.getOrCreateSegmentIfLive(2, context, SEGMENT_INTERVAL * 2L); final LogicalKeyValueSegment segm...
public XAQueueConnection xaQueueConnection(XAQueueConnection connection) { return TracingXAConnection.create(connection, this); }
@Test void xaQueueConnection_wrapsInput() { assertThat(jmsTracing.xaQueueConnection(mock(XAQueueConnection.class))) .isInstanceOf(TracingXAConnection.class); }
protected boolean userIsOwner() { final MantaAccountHomeInfo account = new MantaAccountHomeInfo(host.getCredentials().getUsername(), host.getDefaultPath()); return StringUtils.equals(host.getCredentials().getUsername(), account.getAccountOwner()); }
@Test public void testUserOwnerIdentification() { final MantaSession ownerSession = new MantaSession( new Host( new MantaProtocol(), null, 443, new Credentials("theOwner")), new DisabledX509TrustManager(), new DefaultX509KeyManager(...
@SuppressFBWarnings(justification = "try with resource will clenaup the resources", value = {"OBL_UNSATISFIED_OBLIGATION"}) public List<SuppressionRule> parseSuppressionRules(File file) throws SuppressionParseException { try (FileInputStream fis = new FileInputStream(file)) { return parseSuppres...
@Test public void testParseSuppressionRulesV1dot1() throws Exception { //File file = new File(this.getClass().getClassLoader().getResource("suppressions.xml").getPath()); File file = BaseTest.getResourceAsFile(this, "suppressions_1_1.xml"); SuppressionParser instance = new SuppressionParser(...
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testRMapCacheValues() { final RMapCacheNative<String, String> map = redisson.getMapCacheNative("testRMapCacheValues"); map.put("1234", "5678", Duration.ofMinutes(1)); assertThat(map.values()).containsOnly("5678"); map.destroy(); }
public static long getTimestampMillis(Binary timestampBinary) { if (timestampBinary.length() != 12) { throw new PrestoException(NOT_SUPPORTED, "Parquet timestamp must be 12 bytes, actual " + timestampBinary.length()); } byte[] bytes = timestampBinary.getBytes(); // littl...
@Test public void testGetTimestampMillis() { assertTimestampCorrect("2011-01-01 00:00:00.000000000"); assertTimestampCorrect("2001-01-01 01:01:01.000000001"); assertTimestampCorrect("2015-12-31 23:59:59.999999999"); }
@Override protected Map<String, ConfigValue> validateSourceConnectorConfig(SourceConnector connector, ConfigDef configDef, Map<String, String> config) { Map<String, ConfigValue> result = super.validateSourceConnectorConfig(connector, configDef, config); validateSourceConnectorExactlyOnceSupport(conf...
@Test public void testExactlyOnceSourceSupportValidationOnUnsupportedConnector() { herder = exactlyOnceHerder(); Map<String, String> config = new HashMap<>(); config.put(SourceConnectorConfig.EXACTLY_ONCE_SUPPORT_CONFIG, REQUIRED.toString()); SourceConnector connectorMock = mock(Sou...
@Override public void pickAddress() throws Exception { if (publicAddress != null || bindAddress != null) { return; } try { AddressDefinition publicAddressDef = getPublicAddressByPortSearch(); if (publicAddressDef != null) { publicAddress = ...
@Test public void testBindAddress_whenAddressAlreadyInUse() throws Exception { int port = 6789; config.getNetworkConfig().setPort(port); config.getNetworkConfig().setPortAutoIncrement(false); addressPicker = new DefaultAddressPicker(config, logger); addressPicker.pickAddress...
@Override public Response get() throws InterruptedException { synchronized (this) { while (!isDone) { wait(); } } return response; }
@Test void testSyncGetResponseFailureWithTimeout() throws InterruptedException, TimeoutException { assertThrows(TimeoutException.class, () -> { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); requestFuture.get(100L); }); }
public B executes(Integer executes) { this.executes = executes; return getThis(); }
@Test void executes() { ServiceBuilder builder = new ServiceBuilder(); builder.executes(10); Assertions.assertEquals(10, builder.build().getExecutes()); }
public static Map<String, String> parseToMap(String attributesModification) { if (Strings.isNullOrEmpty(attributesModification)) { return new HashMap<>(); } // format: +key1=value1,+key2=value2,-key3,+key4=value4 Map<String, String> attributes = new HashMap<>(); Stri...
@Test public void parseToMap_EmptyString_ReturnsEmptyMap() { String attributesModification = ""; Map<String, String> result = AttributeParser.parseToMap(attributesModification); assertTrue(result.isEmpty()); }
public static <T> Point<T> interpolate(Point<T> p1, Point<T> p2, Instant targetTime) { checkNotNull(p1, "Cannot perform interpolation when the first input points is null"); checkNotNull(p2, "Cannot perform interpolation when the second input points is null"); checkNotNull(targetTime, "Cannot per...
@Test public void testInterpolatePointWithBadNulCourse() { //The RH message shown in s1 has no course String s1 = "[RH],STARS,GEG,07/08/2017,14:09:11.474,,,,1200,0,0,,47.61734,-117.54339,655,0,0.3008,-0.1445,,,,GEG,,,,,,,IFR,,,,,,,,,,,,{RH}\n"; //The RH message shown in s2 has a course of 2...
@Override public PostgreSQLIdentifierTag getIdentifier() { return PostgreSQLMessagePacketType.DATA_ROW; }
@Test void assertGetIdentifier() { assertThat(new PostgreSQLDataRowPacket(Collections.emptyList()).getIdentifier(), is(PostgreSQLMessagePacketType.DATA_ROW)); }
public Schema toKsqlSchema(final Schema schema) { try { final Schema rowSchema = toKsqlFieldSchema(schema); if (rowSchema.type() != Schema.Type.STRUCT) { throw new KsqlException("KSQL stream/table schema must be structured"); } if (rowSchema.fields().isEmpty()) { throw new K...
@Test public void shouldTranslatePrimitives() { final Schema connectSchema = SchemaBuilder .struct() .field("intField", Schema.INT32_SCHEMA) .field("longField", Schema.INT64_SCHEMA) .field("doubleField", Schema.FLOAT64_SCHEMA) .field("stringField", Schema.STRING_SCHEMA) ...
public void processOnce() throws IOException { // set status of query to OK. ctx.getState().reset(); executor = null; // reset sequence id of MySQL protocol final MysqlChannel channel = ctx.getMysqlChannel(); channel.setSequenceId(0); // read packet from channel ...
@Test public void testInitDb() throws IOException { ConnectContext ctx = initMockContext(mockChannel(initDbPacket), GlobalStateMgr.getCurrentState()); ctx.setCurrentUserIdentity(UserIdentity.ROOT); ctx.setCurrentRoleIds(Sets.newHashSet(PrivilegeBuiltinConstants.ROOT_ROLE_ID)); ctx.se...