focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public JdbcUrl parse(final String jdbcUrl) { Matcher matcher = CONNECTION_URL_PATTERN.matcher(jdbcUrl); ShardingSpherePreconditions.checkState(matcher.matches(), () -> new UnrecognizedDatabaseURLException(jdbcUrl, CONNECTION_URL_PATTERN.pattern().replaceAll("%", "%%"))); String authority = match...
@Test void assertParseMySQLJdbcUrl() { JdbcUrl actual = new StandardJdbcUrlParser().parse("jdbc:mysql://127.0.0.1:3306/demo_ds?useSSL=false&sessionVariables=group_concat_max_len=204800,SQL_SAFE_UPDATES=0"); assertThat(actual.getHostname(), is("127.0.0.1")); assertThat(actual.getPort(), is(33...
@Override public double quantile(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } if (p == 0.0) { return 0; } if (p == 1.0) { return n; } // Starting guess near peak of densit...
@Test public void testQuantile() { System.out.println("quantile"); BinomialDistribution instance = new BinomialDistribution(100, 0.3); instance.rand(); assertEquals(0, instance.quantile(0), 1E-7); assertEquals(0, instance.quantile(0.00000000000000001), 1E-7); assertEq...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { if (tradingRecord != null && !tradingRecord.isClosed()) { Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice(); Num currentPrice = this.referencePrice.getValue(index); N...
@Test public void testNoStopLoss() { ZonedDateTime initialEndDateTime = ZonedDateTime.now(); for (int i = 0; i < 10; i++) { series.addBar(initialEndDateTime.plusDays(i), 100, 105, 95, 100); } AverageTrueRangeStopLossRule rule = new AverageTrueRangeStopLossRule(series, 5...
public PublisherAgreement signPublisherAgreement(UserData user) { checkApiUrl(); var eclipseToken = checkEclipseToken(user); var headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(eclipseToken.accessToken); headers.setAc...
@Test public void testPublisherAgreementAlreadySigned() throws Exception { var user = mockUser(); Mockito.when(restTemplate.postForEntity(any(String.class), any(), eq(String.class))) .thenThrow(new HttpClientErrorException(HttpStatus.CONFLICT)); try { eclipse.signPub...
public boolean intersectsCircle(double pointX, double pointY, double radius) { double halfWidth = getWidth() / 2; double halfHeight = getHeight() / 2; double centerDistanceX = Math.abs(pointX - getCenterX()); double centerDistanceY = Math.abs(pointY - getCenterY()); // is the c...
@Test public void intersectsCircleTest() { Rectangle rectangle1 = create(1, 2, 3, 4); Assert.assertTrue(rectangle1.intersectsCircle(1, 2, 0)); Assert.assertTrue(rectangle1.intersectsCircle(1, 2, 1)); Assert.assertTrue(rectangle1.intersectsCircle(1, 2, 10)); Assert.assertTru...
@Override public void dumpAsCsv(ScoreMatrix scoreMatrix) { if (configuration.getBoolean("sonar.filemove.dumpCsv").orElse(false)) { try { Path tempFile = fs.getTempDir().toPath() .resolve(String.format("score-matrix-%s.csv", ceTask.getUuid())); try (BufferedWriter writer = Files.new...
@Test public void dumpAsCsv_creates_csv_dump_of_score_matrix_if_property_is_true() throws IOException { String taskUuid = "acme"; when(ceTask.getUuid()).thenReturn(taskUuid); settings.setProperty("sonar.filemove.dumpCsv", "true"); underTest.dumpAsCsv(A_SCORE_MATRIX); Collection<File> files = lis...
@Override public String toString() { return "NodeDetails{" + "type=" + type + ", name='" + name + '\'' + ", host='" + host + '\'' + ", port=" + port + ", startedAt=" + startedAt + '}'; }
@Test public void verify_toString() { String name = randomAlphanumeric(3); String host = randomAlphanumeric(10); int port = 1 + random.nextInt(10); long startedAt = 1 + random.nextInt(666); NodeDetails underTest = builderUnderTest .setType(randomType) .setName(name) .setHost(hos...
public void finishCreateReplicaTask(CreateReplicaTask task, TFinishTaskRequest request) { long tabletId = task.getTabletId(); TabletSchedCtx tabletCtx = takeRunningTablets(tabletId); if (tabletCtx == null) { LOG.warn("tablet info does not exist, tablet:{} backend:{}", tabletId, task....
@Test public void testFinishCreateReplicaTask() { long beId = 10001L; long dbId = 10002L; long tblId = 10003L; long partitionId = 10004L; long indexId = 10005L; long tabletId = 10006L; long replicaId = 10007L; long schemaId = indexId; TTabletS...
public ConfigOperateResult insertOrUpdate(String srcIp, String srcUser, ConfigInfo configInfo, Map<String, Object> configAdvanceInfo) { try { ConfigInfoStateWrapper configInfoState = findConfigInfoState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTena...
@Test void testInsertOrUpdateOfException() { String dataId = "dataId"; String group = "group"; String tenant = "tenant"; //mock get config state Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STAT...
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse) || monitoringDisabled || !instanceEnabled) { // si ce n'est pas une requête h...
@Test public void testDoFilterNoHttp() throws ServletException, IOException { final FilterChain servletChain = createNiceMock(FilterChain.class); final ServletRequest servletRequest = createNiceMock(ServletRequest.class); final ServletResponse servletResponse = createNiceMock(ServletResponse.class); replay(ser...
public AmazonInfo build() { return new AmazonInfo(Name.Amazon.name(), metadata); }
@Test public void payloadWithClassAfterMetadata() throws IOException { String json = "{" + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"" + "}"; ...
public Map<String, BitSet> findMatchingRecords(String fieldName, String fieldValue) { Map<String, BitSet> matches = new HashMap<String, BitSet>(); for(HollowTypeReadState typeState : readEngine.getTypeStates()) { augmentMatchingRecords(typeState, fieldName, fieldValue, matches); ...
@Test public void matchesRecordsOfAnyType() { HollowFieldMatchQuery query = new HollowFieldMatchQuery(stateEngine); Map<String, BitSet> matches = query.findMatchingRecords("id", "2"); Assert.assertEquals(2, matches.size()); Assert.assertEquals(1, matches.get("TypeA...
public Optional<BigDecimal> convertToUsd(final BigDecimal amount, final String currency) { if ("USD".equalsIgnoreCase(currency)) { return Optional.of(amount); } return Optional.ofNullable(cachedFixerValues.get(currency.toUpperCase(Locale.ROOT))) .map(conversionRate -> amount.divide(conversion...
@Test void convertToUsd() { final CurrencyConversionManager currencyConversionManager = new CurrencyConversionManager(mock(FixerClient.class), mock(CoinMarketCapClient.class), mock(FaultTolerantRedisCluster.class), Collections.emptyList(), EXECUTOR, Clock.systemUTC()); ...
@Override public void run(DiagnosticsLogWriter writer) { for (; ; ) { Object item = logQueue.poll(); if (item == null) { return; } if (item instanceof LifecycleEvent event) { render(writer, event); } else if (item i...
@Test public void testMembership() { HazelcastInstance instance = hzFactory.newHazelcastInstance(config); assertTrueEventually(() -> { plugin.run(logWriter); assertContains("MemberAdded["); }); instance.shutdown(); assertTrueEventually(() -> { ...
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void LOGBACK744_withColon() throws ScanException { String input = "%d{HH:mm:ss.SSS} host:${host} %logger{36} - %msg%n"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); System.out.println(nodeToStringTran...
@Override public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); }
@Test public void validateSmsCode_used() { // 准备参数 SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { o.setMobile("15601691300"); o.setScene(randomEle(SmsSceneEnum.values()).getScene()); }); // mock 数据 SqlConstants.init(DbTyp...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatSelectQueryCorrectly() { final String statementString = "CREATE STREAM S AS SELECT a.address->city FROM address a;"; final Statement statement = parseSingle(statementString); assertThat(SqlFormatter.formatSql(statement), equalTo("CREATE STREAM S AS SELECT A.ADDRESS->C...
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { super.userEventTriggered(ctx, evt); if (evt instanceof Http2GoAwayFrame) { Http2GoAwayFrame event = (Http2GoAwayFrame) evt; ctx.close(); LOGGER.debug( ...
@Test void testUserEventTriggered() throws Exception { // test Http2GoAwayFrame Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame( Http2Error.NO_ERROR, ByteBufUtil.writeAscii(ByteBufAllocator.DEFAULT, "app_requested")); handler.userEventTriggered(ctx, goAwayFrame); ...
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testNotIn() { assertThat(notIn("s", 7, 8, 9).literals()).hasSize(3); assertThat(notIn("s", 7, 8.1, Long.MAX_VALUE).literals()).hasSize(3); assertThat(notIn("s", "abc", "abd", "abc").literals()).hasSize(3); assertThat(notIn("s").literals()).isEmpty(); assertThat(notIn("s", 5).lite...
@SuppressJava6Requirement(reason = "Guarded with java version check") static String base64(byte[] data) { if (PlatformDependent.javaVersion() >= 8) { return java.util.Base64.getEncoder().encodeToString(data); } String encodedString; ByteBuf encodedData = Unpooled.wrappedB...
@Test public void testBase64() { String base64 = WebSocketUtil.base64(EmptyArrays.EMPTY_BYTES); assertNotNull(base64); assertTrue(base64.isEmpty()); base64 = WebSocketUtil.base64("foo".getBytes(CharsetUtil.UTF_8)); assertEquals(base64, "Zm9v"); base64 = WebSocketUti...
@Override public void commitSync() { commitSync(Duration.ofMillis(defaultApiTimeoutMs)); }
@Test public void testCommitSyncAwaitsCommitAsyncButDoesNotFail() { final TopicPartition tp = new TopicPartition("foo", 0); final CompletableFuture<Void> asyncCommitFuture = setUpConsumerWithIncompleteAsyncCommit(tp); // Mock to complete sync event completeCommitSyncApplicationEvent...
public static Search<?> searchResourcesWithGenericParameters(String fhirStore) { return new Search<>(fhirStore); }
@Test public void test_FhirIO_failedSearchesWithGenericParameters() { FhirSearchParameter<List<String>> input = FhirSearchParameter.of("resource-type-1", null); FhirIO.Search.Result searchResult = pipeline .apply( Create.of(input) .withCoder(FhirSearchPa...
@Override public void validateAction( RepositoryOperation... operations ) throws KettleException { for ( RepositoryOperation operation : operations ) { switch ( operation ) { case EXECUTE_TRANSFORMATION: case EXECUTE_JOB: checkOperationAllowed( EXECUTE_CONTENT_ACTION ); ...
@Test( expected = KettleException.class ) public void exceptionThrown_WhenOperationNotAllowed_ExecuteOperation() throws Exception { setOperationPermissions( IAbsSecurityProvider.EXECUTE_CONTENT_ACTION, false ); provider.validateAction( RepositoryOperation.EXECUTE_TRANSFORMATION ); }
@Override public long sleepTime(final long attempt) { checkArgument(attempt >= 0, "attempt must not be negative (%s)", attempt); final long exponentialSleepTime = initialWait * Math.round(Math.pow(2, attempt)); return exponentialSleepTime >= 0 && exponentialSleepTime < maxWait ...
@Test void testMaxSleepTime() { final long sleepTime = new ExponentialWaitStrategy(1, 1).sleepTime(100); assertThat(sleepTime).isEqualTo(1L); }
public long computeInflightTotalDiff() { long diffTotal = 0L; for (Entry<MessageQueue, OffsetWrapper> entry : this.offsetTable.entrySet()) { diffTotal += entry.getValue().getPullOffset() - entry.getValue().getConsumerOffset(); } return diffTotal; }
@Test public void testComputeInflightTotalDiff() { ConsumeStats stats = new ConsumeStats(); MessageQueue messageQueue = Mockito.mock(MessageQueue.class); OffsetWrapper offsetWrapper = Mockito.mock(OffsetWrapper.class); Mockito.when(offsetWrapper.getBrokerOffset()).thenReturn(3L); ...
@Override public List<Object> apply(ConsumerRecord<K, V> record) { RecordTranslator<K, V> trans = topicToTranslator.getOrDefault(record.topic(), defaultTranslator); return trans.apply(record); }
@Test public void testNullTranslation() { ByTopicRecordTranslator<String, String> trans = new ByTopicRecordTranslator<>((r) -> null, new Fields("key")); ConsumerRecord<String, String> cr = new ConsumerRecord<>("TOPIC 1", 100, 100, "THE KEY", "THE VALUE"); assertNull(trans.app...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); for (String pool : POOLS) { for (int i = 0; i < ATTRIBUTES.length; i++) { final String attribute = ATTRIBUTES[i]; final String name = NAMES[i]; ...
@Test public void includesAGaugeForMappedCount() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get("mapped.count"); when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100); assertThat(gauge.getValue()) .isEqualTo(100); }
@Override public void close() { try { out.close(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test void close() { out.append("Hello"); assertThat(bytes, bytes(equalTo(""))); out.close(); assertThat(bytes, bytes(equalTo("Hello"))); }
@Override public ResourceUsage getMemory() { return memory; }
@Test public void testLocalBrokerDataDeserialization() throws JsonProcessingException { ObjectReader LOAD_REPORT_READER = ObjectMapperFactory.getMapper().reader() .forType(LoadManagerReport.class); String data = "{\"webServiceUrl\":\"http://10.244.2.23:8080\",\"webServiceUrlTls\":\"h...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String targetObjectId = reader.readLine(); String methodName = reader.readLine(); List<Object> arguments = getArguments(reader); ReturnObject returnObject = invokeMethod(metho...
@Test public void testVoidMethod() { String inputCommand = target + "\nmethod2\nsThis is a\tString\\n\ne\n"; try { command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); } catch (Exception e) { e.printStackTrace(); fail(); } }
public static KeyValueBytesStoreSupplier persistentKeyValueStore(final String name) { Objects.requireNonNull(name, "name cannot be null"); return new RocksDBKeyValueBytesStoreSupplier(name, false); }
@Test public void shouldCreateRocksDbStore() { assertThat( Stores.persistentKeyValueStore("store").get(), allOf(not(instanceOf(RocksDBTimestampedStore.class)), instanceOf(RocksDBStore.class))); }
public void setup(final Map<String, InternalTopicConfig> topicConfigs) { log.info("Starting to setup internal topics {}.", topicConfigs.keySet()); final long now = time.milliseconds(); final long deadline = now + retryTimeoutMs; final Map<String, Map<String, String>> streamsSideTopicCo...
@Test public void shouldThrowWhenCreateTopicsThrowsUnexpectedException() { final AdminClient admin = mock(AdminClient.class); final StreamsConfig streamsConfig = new StreamsConfig(config); final InternalTopicManager topicManager = new InternalTopicManager(time, admin, streamsConfig); ...
public static HuaweiLtsLogCollectClient getHuaweiLtsLogCollectClient() { return HUAWEI_LTS_LOG_COLLECT_CLIENT; }
@Test public void testGetHuaweiLtsLogCollectClient() { Assertions.assertEquals(LoggingHuaweiLtsPluginDataHandler.getHuaweiLtsLogCollectClient().getClass(), HuaweiLtsLogCollectClient.class); }
public IntervalSet negate() { if (!isValid()) { return IntervalSet.ALWAYS; } if (mStartMs == MIN_MS) { if (mEndMs == MAX_MS) { // this is ALWAYS, so the negation is never return IntervalSet.NEVER; } return new IntervalSet(after(mEndMs)); } // start is after mi...
@Test public void negateNever() { List<Interval> neg = Interval.NEVER.negate().getIntervals(); Assert.assertTrue(neg.size() == 1); Interval in = neg.get(0); Assert.assertEquals(Interval.ALWAYS, in); }
@Override public Set<Link> getDeviceIngressLinks(DeviceId deviceId) { return filter(links.values(), link -> deviceId.equals(link.dst().deviceId())); }
@Test public final void testGetDeviceIngressLinks() { LinkKey linkId1 = LinkKey.linkKey(new ConnectPoint(DID1, P1), new ConnectPoint(DID2, P2)); LinkKey linkId2 = LinkKey.linkKey(new ConnectPoint(DID2, P2), new ConnectPoint(DID1, P1)); LinkKey linkId3 = LinkKey.linkKey(new ConnectPoint(DID1,...
@Override public Decoder<Object> getMapValueDecoder() { return mapValueDecoder; }
@Test public void shouldDeserializeTheMapCorrectly() throws Exception { ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(); buf.writeBytes(new ObjectMapper().writeValueAsBytes(map)); assertThat(mapCodec.getMapValueDecoder().decode(buf, new State())) .isInstanceOf(Map.class) ...
public void handle(SeckillWebMockRequestDTO request) { prePreRequestHandlers.stream().sorted(Comparator.comparing(Ordered::getOrder)) .forEach(it -> { try { it.handle(request); } catch (Exception e) { log.war...
@Test public void shouldHandleRequestEvenWhenOneHandlerFails() { SeckillWebMockRequestDTO request = new SeckillWebMockRequestDTO(); doThrow(new RuntimeException()).when(handler1).handle(request); doNothing().when(handler2).handle(request); preRequestPipeline.handle(request); ...
CepRuntimeContext(final RuntimeContext runtimeContext) { this.runtimeContext = checkNotNull(runtimeContext); }
@Test public void testCepRuntimeContext() { final String taskName = "foobarTask"; final OperatorMetricGroup metricGroup = UnregisteredMetricsGroup.createOperatorMetricGroup(); final int numberOfParallelSubtasks = 43; final int indexOfSubtask = 42; final int at...
public static URI getCanonicalUri(URI uri, int defaultPort) { // skip if there is no authority, ie. "file" scheme or relative uri String host = uri.getHost(); if (host == null) { return uri; } String fqHost = canonicalizeHost(host); int port = uri.getPort(); // short out if already can...
@Test public void testCanonicalUriWithPort() { URI uri; uri = NetUtils.getCanonicalUri(URI.create("scheme://host:123"), 456); assertEquals("scheme://host.a.b:123", uri.toString()); uri = NetUtils.getCanonicalUri(URI.create("scheme://host:123/"), 456); assertEquals("scheme://host.a.b:123/", uri.t...
public void maybeFlushBatches(LeaderAndEpoch leaderAndEpoch) { MetadataProvenance provenance = new MetadataProvenance(lastOffset, lastEpoch, lastContainedLogTimeMs); LogDeltaManifest manifest = LogDeltaManifest.newBuilder() .provenance(provenance) .leaderAndEpoch(leaderAndEpoch) ...
@Test public void testMultipleTransactionsInOneBatch() { List<ApiMessageAndVersion> batchRecords = new ArrayList<>(); batchRecords.addAll(TOPIC_TXN_BATCH_1); batchRecords.addAll(TOPIC_TXN_BATCH_2); batchRecords.addAll(TXN_BEGIN_SINGLETON); batchRecords.addAll(TOPIC_NO_TXN_BAT...
public static SerializerAdapter createSerializerAdapter(Serializer serializer) { final SerializerAdapter s; if (serializer instanceof StreamSerializer streamSerializer) { s = new StreamSerializerAdapter(streamSerializer); } else if (serializer instanceof ByteArraySerializer arraySeri...
@Test public void testCreateSerializerAdapter() { // ArrayStreamSerializer is instance of StreamSerializer, hence using it as parameter SerializerAdapter streamSerializerAdapter = SerializationUtil.createSerializerAdapter(new ArrayStreamSerializer()); assertEquals(streamSerializerAdapter.get...
public static boolean exists(String name) { name = getWellFormName(name); return STRING_ENV_MAP.containsKey(name); }
@Test public void testExistsForBlankName() { assertFalse(Env.exists("")); assertFalse(Env.exists(" ")); assertFalse(Env.exists(null)); }
@CheckForNull public String getExternalUserAuthentication() { SecurityRealm realm = securityRealmFactory.getRealm(); return realm == null ? null : realm.getName(); }
@Test public void getExternalUserAuthentication_whenNotDefined_shouldReturnNull() { assertThat(commonSystemInformation.getExternalUserAuthentication()) .isNull(); }
public static Dish createDish(Recipe recipe) { Map<Product, BigDecimal> calculatedRecipeToGram = new HashMap<>(); recipe.getIngredientsProportion().forEach(((product, proportion) -> { calculatedRecipeToGram.put(product, recipe.getBasePortionInGrams() .multiply(proportion....
@Test void createDish_numberOfFillers() { Dish dish = Dish.createDish(recipe, BigDecimal.valueOf(1300)); assertAll("Should be correct", () -> assertEquals(3, dish.getNumberOfFillers().size()), () -> assertEquals(1, dish.getNumberOfFillers().get(Filler.FAT)) ...
public long computeExpirationTime(final String pHttpExpiresHeader, final String pHttpCacheControlHeader, final long pNow) { final Long override = Configuration.getInstance().getExpirationOverrideDuration(); if (override != null) { return pNow + override; } final long extensi...
@Test public void testCustomExpirationTimeWithHttpConnection() { final long twentyMinutesInMillis = 20 * 60 * 1000; final long thirtyMinutesInMillis = 30 * 60 * 1000; final HttpURLConnection dummyConnection = new HttpURLConnection(null) { @Override public void disconn...
public Map<String, String> clientTags() { return data.clientTags().stream() .collect( Collectors.toMap( clientTag -> new String(clientTag.key(), StandardCharsets.UTF_8), clientTag -> new String(clientTag.value(), StandardCharsets.UTF_8) ...
@Test public void shouldReturnMapOfClientTagsOnVersion11() { final SubscriptionInfo info = new SubscriptionInfo(11, LATEST_SUPPORTED_VERSION, PID_1, "localhost:80", TASK_OFFSET_SUMS, IGNORED_UNIQUE_FIELD, IGNORED_ERROR_CODE, CLIENT_TAGS); assertThat(info.clientTags(), is...
public Map<String, String> getTypes(final Set<String> streamIds, final Set<String> fields) { final Map<String, Set<String>> allFieldTypes = this.get(streamIds); final Map<String, String> result = new HashMap<>(fields.size()); fields.forEach(field -> { ...
@Test void getTypesReturnsEmptyMapIfFieldTypesAreEmpty() { final Pair<IndexFieldTypesService, StreamService> services = mockServices(); final FieldTypesLookup lookup = new FieldTypesLookup(services.getLeft(), services.getRight()); assertThat(lookup.getTypes(Set.of("SomeStream"), Set.of("some...
@Override public void removeRule(final RuleData ruleData) { String key = CacheKeyUtils.INST.getKey(ruleData); CACHED_HANDLE.get().removeHandle(key); FlowRuleManager.loadRules(FlowRuleManager.getRules() .stream() .filter(r -> !r.getResource().equals(key)) ...
@Test public void removeRule() { RuleData data = new RuleData(); data.setSelectorId("sentinel"); data.setId("removeRule"); SentinelHandle sentinelHandle = new SentinelHandle(); sentinelHandle.setFlowRuleCount(10); sentinelHandle.setFlowRuleGrade(0); sentinelHa...
@Override public byte[] retrieveSecret(SecretIdentifier identifier) { if (identifier != null && identifier.getKey() != null && !identifier.getKey().isEmpty()) { try { lock.lock(); loadKeyStore(); SecretKeyFactory factory = SecretKeyFactory.getInsta...
@Test public void retrieveWithInvalidInput() { assertThat(keyStore.retrieveSecret(null)).isNull(); }
@Override public GroupAssignment assign( GroupSpec groupSpec, SubscribedTopicDescriber subscribedTopicDescriber ) throws PartitionAssignorException { if (groupSpec.memberIds().isEmpty()) { return new GroupAssignment(Collections.emptyMap()); } else if (groupSpec.subscr...
@Test public void testStaticMembership() throws PartitionAssignorException { SubscribedTopicDescriber subscribedTopicMetadata = new SubscribedTopicDescriberImpl( Collections.singletonMap( topic1Uuid, new TopicMetadata( topic1Uuid, ...
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldBuildAssertTopic() { // Given: final SingleStatementContext stmt = givenQuery("ASSERT TOPIC X;"); // When: final AssertTopic assertTopic = (AssertTopic) builder.buildStatement(stmt); // Then: assertThat(assertTopic.getTopic(), is("X")); assertThat(assertTo...
public ListStateDescriptor(String name, Class<T> elementTypeClass) { super(name, new ListTypeInfo<>(elementTypeClass), null); }
@Test void testListStateDescriptor() throws Exception { TypeSerializer<String> serializer = new KryoSerializer<>(String.class, new SerializerConfigImpl()); ListStateDescriptor<String> descr = new ListStateDescriptor<>("testName", serializer); assertThat(descr.getName()).is...
public void initializeTypeState(Class<?> clazz) { Objects.requireNonNull(clazz); getTypeMapper(clazz, null, null); }
@Test public void testFailsToCreateSchemaIfThereAreDuplicateFields() { try { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(Child.class); Assert.fail("Expected Exception not thrown"); } catch (IllegalArgumentExcept...
@Override public WatchKey register(final Watchable folder, final WatchEvent.Kind<?>[] events, final WatchEvent.Modifier... modifiers) throws IOException { if(null == monitor) { monitor = FileSystems.getDefault().newWatchService(); } final WatchKey key...
@Test public void testRegister() throws Exception { final RegisterWatchService fs = new NIOEventWatchService(); final Watchable folder = Paths.get( File.createTempFile(UUID.randomUUID().toString(), "t").getParent()); final WatchKey key = fs.register(folder, new WatchEvent.Kind[]{...
public static <E> ArrayList<E> newArrayList() { return new ArrayList<>(); }
@Test public void testAddToEmptyArrayList() { List<String> list = Lists.newArrayList(); list.add("record1"); Assert.assertEquals(1, list.size()); Assert.assertEquals("record1", list.get(0)); }
@Override public int sortTo(String destName, SortOrder order) { return get(sortToAsync(destName, order)); }
@Test public void testSortTo() { RSet<String> list = redisson.getSet("list", IntegerCodec.INSTANCE); list.add("1"); list.add("2"); list.add("3"); assertThat(list.sortTo("test3", SortOrder.DESC)).isEqualTo(3); RList<String> list2 = redisson.getList("test3", StringCode...
@Override public URL getResource(String name) { ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resource '{}'", name); for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) { URL url = null; ...
@Test void parentLastGetResourceExistsInBothParentAndPlugin() throws URISyntaxException, IOException { URL resource = parentLastPluginClassLoader.getResource("META-INF/file-in-both-parent-and-plugin"); assertFirstLine("plugin", resource); }
public static ConjunctFuture<Void> completeAll( Collection<? extends CompletableFuture<?>> futuresToComplete) { return new CompletionConjunctFuture(futuresToComplete); }
@Test void testCompleteAll() { final CompletableFuture<String> inputFuture1 = new CompletableFuture<>(); final CompletableFuture<Integer> inputFuture2 = new CompletableFuture<>(); final List<CompletableFuture<?>> futuresToComplete = Arrays.asList(inputFuture1, inputFuture2);...
@Override public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionOffset, final int connectionSize, final ConnectionMode connectionMode) throws SQLException { Preconditions.checkNotNull(databaseName, "Curre...
@Test void assertGetConnectionsAndFailedToReplaySessionVariables() throws SQLException { connectionSession.getRequiredSessionVariableRecorder().setVariable("key", "value"); Connection connection = null; SQLException expectedException = new SQLException(""); try { connecti...
public static Compression.Algorithm getHFileCompressionAlgorithm(Map<String, String> paramsMap) { String algoName = paramsMap.get(HFILE_COMPRESSION_ALGORITHM_NAME.key()); if (StringUtils.isNullOrEmpty(algoName)) { return Compression.Algorithm.GZ; } return Compression.Algorithm.valueOf(algoName.toU...
@Test public void testGetDefaultHFileCompressionAlgorithm() { assertEquals(Compression.Algorithm.GZ, getHFileCompressionAlgorithm(Collections.emptyMap())); }
public void logSlowQuery(final Statement statement, final long startTimeNanos, final JdbcSessionContext context) { if ( logSlowQuery < 1 ) { return; } if ( startTimeNanos <= 0 ) { throw new IllegalArgumentException( "startTimeNanos [" + startTimeNanos + "] should be greater than 0" ); } final long quer...
@Test public void testLogSlowQueryFromStatementWhenLoggingDisabled() { SqlStatementLogger sqlStatementLogger = new SqlStatementLogger( false, false, false, 0L ); AtomicInteger callCounterToString = new AtomicInteger(); Statement statement = mockStatementForCountingToString( callCounterToString ); sqlStatement...
protected final void ensureCapacity(final int index, final int length) { if (index < 0 || length < 0) { throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length); } final long resultingPosition = index + (long)length; final int c...
@Test void ensureCapacityThrowsIndexOutOfBoundsExceptionIfIndexIsNegative() { final ExpandableDirectByteBuffer buffer = new ExpandableDirectByteBuffer(1); final IndexOutOfBoundsException exception = assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(-3, ...
public static void createDir(String path) throws IOException { Files.createDirectories(Paths.get(path)); }
@Test public void createDir() throws IOException { File tempDir = new File(mTestFolder.getRoot(), "tmp"); FileUtils.createDir(tempDir.getAbsolutePath()); assertTrue(FileUtils.exists(tempDir.getAbsolutePath())); assertTrue(tempDir.delete()); }
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query));...
@Test public void fail_to_create_query_on_qualifier_when_operator_is_not_equal() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(GT).setValue("APP").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) ...
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) { final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps()); map.put( MetricCollectors.RESOURCE_LABEL_PREFIX + StreamsConfig.APPLICATION_ID_CONFIG, applicationId ); // Streams cli...
@Test public void shouldFailOnProductionErrorByDefault() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.emptyMap()); final Object result = ksqlConfig.getKsqlStreamConfigProps() .get(StreamsConfig.DEFAULT_PRODUCTION_EXCEPTION_HANDLER_CLASS_CONFIG); assertThat(result, equalTo(LogAndFailP...
@Override public boolean askForNotificationPostPermission(@NonNull Activity activity) { return PermissionRequestHelper.check( activity, PermissionRequestHelper.NOTIFICATION_PERMISSION_REQUEST_CODE); }
@Test @Config(sdk = Build.VERSION_CODES.S_V2) public void testAlwaysHavePermissionToPostNotification() { try (var scenario = ActivityScenario.launch(TestFragmentActivity.class)) { scenario .moveToState(Lifecycle.State.RESUMED) .onActivity( activity -> { As...
@Override public void begin() { if (!connection.getConnectionSession().getTransactionStatus().isInTransaction()) { connection.getConnectionSession().getTransactionStatus().setInTransaction(true); getTransactionContext().beginTransaction(String.valueOf(transactionType)); c...
@Test void assertBeginForLocalTransaction() { ContextManager contextManager = mockContextManager(TransactionType.LOCAL); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); newBackendTransactionManager(TransactionType.LOCAL, false); backendTransactionMana...
public static Builder newBuilder() { return new AutoValue_DLPInspectText.Builder(); }
@Test public void throwsExceptionWhenDeidentifyConfigAndTemplatesAreEmpty() { assertThrows( "Either inspectTemplateName or inspectConfig must be supplied!", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) ...
public Result doWork() { if (prepared) throw new IllegalStateException("Call doWork only once!"); prepared = true; if (!graph.isFrozen()) { throw new IllegalStateException("Given BaseGraph has not been frozen yet"); } if (chStore.getShortcuts() > 0) { ...
@Test public void testMoreComplexGraph() { initShortcutsGraph(g, speedEnc); PrepareContractionHierarchies prepare = createPrepareContractionHierarchies(g); useNodeOrdering(prepare, new int[]{0, 5, 6, 7, 8, 10, 11, 13, 15, 1, 3, 9, 14, 16, 12, 4, 2}); PrepareContractionHierarchies.Res...
@Override public void setNoMorePages() { PendingRead pendingRead; synchronized (this) { state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); noMorePages.set(true); pendingRead = this.pendingRead; this.pendingRead = null; log.info("Task %s:...
@Test public void testSimpleInMemory() { SpoolingOutputBuffer buffer = createSpoolingOutputBuffer(); // add three pages for (int i = 0; i < 2; i++) { addPage(buffer, createPage(i)); } compareTotalBuffered(buffer, 2); assertBufferResultEquals(TYPES, g...
public void setExpression(final String expression) throws IllegalExpressionException { MQELexer lexer = new MQELexer(CharStreams.fromString(expression)); lexer.addErrorListener(new ParseErrorListener()); MQEParser parser = new MQEParser(new CommonTokenStream(lexer)); parser.addErrorListe...
@Test public void testExpressionVerify() throws IllegalExpressionException { AlarmRule rule = new AlarmRule(); //normal common metric rule.setExpression("sum(service_percent < 85) >= 3"); //normal labeled metric //4xx + 5xx > 10 rule.setExpression("sum(aggregate_label...
@Override public SccResult<V, E> search(Graph<V, E> graph, EdgeWeigher<V, E> weigher) { SccResult<V, E> result = new SccResult<>(graph); for (V vertex : graph.getVertexes()) { VertexData data = result.data(vertex); if (data == null) { connect(graph, vertex, we...
@Test public void twoWeaklyConnectedClusters() { graph = new AdjacencyListsGraph<>(vertexes(), of(new TestEdge(A, B), new TestEdge(B, C), new TestEdge(C, D), ...
public static UriTemplate create(String template, Charset charset) { return new UriTemplate(template, true, charset); }
@Test void encodeVariables() { String template = "https://www.example.com/{first}/{last}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); Map<String, Object> variables = new LinkedHashMap<>(); variables.put("first", "John Jacob"); variables.put("last", "Jingleheimer Schmidt");...
public String write(final String rendered, final String inputFileName, final File outputPath) throws IOException { Path writeOutputPath = outputFile(inputFileName, outputPath.getPath()); Files.writeString(writeOutputPath, rendered); return writeOutputPath.toString(); }
@Test public void testWrite() throws IOException { Path path = Paths.get(temporaryDirectory.getPath()); String content = "x y z"; String outputPathStr = fileUtil.write(content, FOOBAR, path.toFile()); Path outputPath = Paths.get((outputPathStr)); String result = Files.rea...
boolean isMapped(String userId) { return idToDirectoryNameMap.containsKey(getIdStrategy().keyFor(userId)); }
@Test public void testIsMapped() throws IOException { UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE); String user1 = "user1"; File directory = mapper.putIfAbsent(user1, true); assertThat(mapper.isMapped(user1), is(true)); }
public static boolean isTimeoutException(Throwable exception) { if (exception == null) return false; if (exception instanceof ExecutionException) { exception = exception.getCause(); if (exception == null) return false; } return exception instanceof TimeoutExceptio...
@Test public void testExecutionExceptionWithNullCauseIsNotTimeoutException() { assertFalse(isTimeoutException(new ExecutionException(null))); }
@Override @SuppressWarnings("rawtypes") public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String,...
@Test public void reportsLongGaugeValues() throws Exception { reporter.report(map("gauge", gauge(1L)), map(), map(), map(), map()); final InOrder inOrder = inOrder(graphite); inOrder.verify(graphite).connect(); inOrder.verify(graphite)...
@Override public PipelineDef parse(Path pipelineDefPath, Configuration globalPipelineConfig) throws Exception { return parse(mapper.readTree(pipelineDefPath.toFile()), globalPipelineConfig); }
@Test void testOverridingGlobalConfig() throws Exception { URL resource = Resources.getResource("definitions/pipeline-definition-full.yaml"); YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser(); PipelineDef pipelineDef = parser.parse( ...
public static int compareVersion(final String versionA, final String versionB) { final String[] sA = versionA.split("\\."); final String[] sB = versionB.split("\\."); int expectSize = 3; if (sA.length != expectSize || sB.length != expectSize) { throw new IllegalArgumentExcept...
@Test void testVersionCompareGt() { assertTrue(VersionUtils.compareVersion("1.2.2", "1.2.1") > 0); assertTrue(VersionUtils.compareVersion("2.2.0", "1.2.0") > 0); assertTrue(VersionUtils.compareVersion("1.3.0", "1.2.0") > 0); }
@SuppressWarnings("unchecked") public static <T> NFAFactory<T> compileFactory( final Pattern<T, ?> pattern, boolean timeoutHandling) { if (pattern == null) { // return a factory for empty NFAs return new NFAFactoryImpl<>( 0, Collect...
@Test public void testMultipleWindowTimeWithZeroLength() { Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .followedBy("middle") .within(Time.seconds(10)) .followedBy("then") .within(Tim...
public final void isSameInstanceAs(@Nullable Object expected) { if (actual != expected) { failEqualityCheck( SAME_INSTANCE, expected, /* * Pass through *whether* the values are equal so that failEqualityCheck() can print that * information. But remove the de...
@Test public void isSameInstanceAsWithSameObject() { Object a = new Object(); Object b = a; assertThat(a).isSameInstanceAs(b); }
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 reorderRowToMessage() { Schema schema = Schema.builder() .addByteArrayField(RowHandler.MESSAGE_KEY_FIELD) .addByteArrayField(RowHandler.PAYLOAD_FIELD) .build(); Schema rowSchema = Schema.builder() .addByteArrayField(RowHandler.P...
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testJsonConversionOfIgnoredProperty() throws Exception { IgnoredProperty options = PipelineOptionsFactory.as(IgnoredProperty.class); options.setValue("TestValue"); IgnoredProperty options2 = serializeDeserialize(IgnoredProperty.class, options); assertNull(options2.getValue()); }
static StaticDataTask fromJson(JsonNode jsonNode) { Preconditions.checkArgument(jsonNode != null, "Invalid JSON node for data task: null"); Preconditions.checkArgument( jsonNode.isObject(), "Invalid JSON node for data task: non-object (%s)", jsonNode); Schema schema = SchemaParser.fromJson(JsonUtil...
@Test public void missingFields() throws Exception { ObjectMapper mapper = new ObjectMapper(); String missingSchemaStr = "{}"; JsonNode missingSchemaNode = mapper.reader().readTree(missingSchemaStr); assertThatThrownBy(() -> DataTaskParser.fromJson(missingSchemaNode)) .isInstanceOf(IllegalArg...
public org.slf4j.Logger logger() { if (this.logger == null) { LoggerContext loggerContext = new LoggerContext(); LogbackMDCAdapter mdcAdapter = new LogbackMDCAdapter(); loggerContext.setMDCAdapter(mdcAdapter); loggerContext.start(); this.logger = log...
@Test void logs() { List<LogEntry> logs = new CopyOnWriteArrayList<>(); List<LogEntry> matchingLog; Flux<LogEntry> receive = TestsUtils.receive(logQueue, either -> logs.add(either.getLeft())); Flow flow = TestsUtils.mockFlow(); Execution execution = TestsUtils.mockExecution(...
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = ...
@Test void testException() throws Exception { Map map = new HashMap(); map.put("message", "dubbo exception"); Object o = PojoUtils.realize(map, RuntimeException.class); assertEquals(((Throwable) o).getMessage(), "dubbo exception"); }
public Map<String, String> connectorBaseConfig(SourceAndTarget sourceAndTarget, Class<?> connectorClass) { Map<String, String> props = new HashMap<>(); props.putAll(rawProperties); props.keySet().retainAll(allConfigNames()); props.putAll(stringsWithPrefix(CONFIG_PROVIDERS_CONFI...
@Test public void testConfigBackwardsCompatibilitySourceTarget() { MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps( "clusters", "a, b", "source->target.topics.blacklist", "topic3", "source->target.groups.blacklist", "group-7", "topic.filter.cl...
public static Duration longest(Duration duration1, Duration duration2) { return duration1.compareTo(duration2) > 0 ? duration1 : duration2; }
@Test public void longest() { Duration d1 = Duration.ofMinutes(1); // shorter Duration d2 = Duration.ofMinutes(1); // longer assertEquals(d2, TimeUtils.longest(d1, d2)); assertEquals(d2, TimeUtils.longest(d2, d1)); assertEquals(d1, TimeUtils.longest(d1, d1)); assertEq...
@Override public BrokerCapacityInfo capacityForBroker(String rack, String host, int brokerId, long timeoutMs, boolean allowCapacityEstimation) throws BrokerCapacityResolutionException { if (brokerId >= 0) { BrokerCapacityInfo capacity = capacitiesForBrokers.get(brokerId); if (capacity != null) {...
@Test public void testParseConfigJbodFile() throws TimeoutException, BrokerCapacityResolutionException { BrokerCapacityConfigResolver configResolver = getBrokerCapacityConfigResolver("testCapacityConfigJBOD.json", this.getClass()); assertEquals(2000000.0, configResolver.capacityForBroker("", "", 0, BROKER_CA...
public static Optional<Expression> convert( org.apache.flink.table.expressions.Expression flinkExpression) { if (!(flinkExpression instanceof CallExpression)) { return Optional.empty(); } CallExpression call = (CallExpression) flinkExpression; Operation op = FILTERS.get(call.getFunctionDefi...
@Test public void testNotEqualsNaN() { UnboundPredicate<Float> expected = org.apache.iceberg.expressions.Expressions.notNaN("field3"); Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert( resolve(Expressions.$("field3").isNotEqual(Expressions.lit(Float.NaN)))...
public static SslProvider chooseSslProvider() { // Use openssl only if available and has ALPN support (ie. version > 1.0.2). SslProvider sslProvider; if (ALLOW_USE_OPENSSL.get() && OpenSsl.isAvailable() && SslProvider.isAlpnSupported(SslProvider.OPENSSL)) { sslProvider = SslProvider....
@Test void testDefaultSslProviderIsOpenSsl() { assertEquals(SslProvider.OPENSSL, BaseSslContextFactory.chooseSslProvider()); }
@Override public void cleanup() { stopComponents(); }
@Test public void cleanup_does_not_fail_even_if_stop_of_component_fails() { parent.add(StopFailing.class); MigrationContainerImpl underTest = new MigrationContainerImpl(parent, NoOpExecutor.class); underTest.cleanup(); }
protected static VplsOperation getOptimizedVplsOperation(Deque<VplsOperation> operations) { if (operations.isEmpty()) { return null; } // no need to optimize if the queue contains only one operation if (operations.size() == 1) { return operations.getFirst(); ...
@Test public void testOptimizeOperationsAToR() { Deque<VplsOperation> operations = new ArrayDeque<>(); VplsData vplsData = VplsData.of(VPLS1); vplsData.addInterfaces(ImmutableSet.of(V100H1)); VplsOperation vplsOperation = VplsOperation.of(vplsData, ...
public OneMessageTransfer(ByteBuffer byteBufferHeader, SelectMappedBufferResult selectMappedBufferResult) { this.byteBufferHeader = byteBufferHeader; this.selectMappedBufferResult = selectMappedBufferResult; }
@Test public void OneMessageTransferTest() { ByteBuffer byteBuffer = ByteBuffer.allocate(20); byteBuffer.putInt(20); SelectMappedBufferResult selectMappedBufferResult = new SelectMappedBufferResult(0,byteBuffer,20,new DefaultMappedFile()); OneMessageTransfer manyMessageTransfer = new...
public SearchOptions setPage(int page, int pageSize) { checkArgument(page >= 1, "Page must be greater or equal to 1 (got " + page + ")"); setLimit(pageSize); int lastResultIndex = page * pageSize; checkArgument(lastResultIndex <= MAX_RETURNABLE_RESULTS, "Can return only the first %s results. %sth result...
@Test public void fail_if_result_after_first_10_000() { assertThatThrownBy(() -> underTest.setPage(21, 500)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Can return only the first 10000 results. 10500th result asked."); }
Map<String, File> scanExistingUsers() throws IOException { Map<String, File> users = new HashMap<>(); File[] userDirectories = listUserDirectories(); if (userDirectories != null) { for (File directory : userDirectories) { String userId = idStrategy.idFromFilename(dire...
@Test public void scanExistingUsersBasic() throws IOException { UserIdMigrator migrator = createUserIdMigrator(); Map<String, File> userMappings = migrator.scanExistingUsers(); assertThat(userMappings.keySet(), hasSize(2)); assertThat(userMappings.keySet(), hasItems("admin", "jane"))...
@Override public String getUrl() { return url != null ? url.originalArgument() : null; }
@Test void shouldReturnNullIfUrlForMaterialNotSpecified() { HgMaterialConfig config = hg(); assertThat(config.getUrl()).isNull(); }
public static <V> Read<V> read() { return new AutoValue_SparkReceiverIO_Read.Builder<V>().build(); }
@Test public void testReadObjectCreationFailsIfPullFrequencySecIsNull() { assertThrows( IllegalArgumentException.class, () -> SparkReceiverIO.<String>read().withPullFrequencySec(null)); }
@Override public MepLtCreate decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { return null; } JsonNode linktraceNode = json.get(LINKTRACE); JsonNode remoteMepIdNode = linktraceNode.get(REMOTE_MEP_ID); JsonNode remoteMepMacNo...
@Test public void testDecodeMepLtCreateMepId() throws JsonProcessingException, IOException { String linktraceString = "{\"linktrace\": { " + "\"remoteMepId\": 20," + "\"defaultTtl\": 21," + "\"transmitLtmFlags\": \"use-fdb-only\"}}"; InputStream in...
protected Timestamp convertBigNumberToTimestamp( BigDecimal bd ) { if ( bd == null ) { return null; } return convertIntegerToTimestamp( bd.longValue() ); }
@Test public void testConvertBigNumberToTimestamp_Nanoseconds() throws KettleValueException { System.setProperty( Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE, Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE_NANOSECONDS ); ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp(); Timestamp re...