focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Optional<BoolQueryBuilder> getPostFilters() { return toBoolQuery(postFilters, (e, v) -> true); }
@Test public void getPostFilters_returns_empty_when_no_declared_topAggregation() { AllFilters allFilters = randomNonEmptyAllFilters(); RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, Collections.emptySet()); assertThat(underTest.getPostFilters()).isEmpty(); }
public static Optional<String> getSystemProperty(String propertyName) { return Optional.ofNullable(getSystemProperty(propertyName, null)); }
@Test public void getSystemProperty_whenPropertyNotExistsWithDefaultValue_returnsDefaultValue() { assertThat(TsunamiConfig.getSystemProperty(TEST_PROPERTY, "Default")).isEqualTo("Default"); }
@Override protected void processOptions(LinkedList<String> args) { CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, OPTION_QUOTA, OPTION_HUMAN, OPTION_HEADER, OPTION_QUOTA_AND_USAGE, OPTION_EXCLUDE_SNAPSHOT, OPTION_ECPOLICY, OPTION_SNAPSHOT_COUNT); cf.addOptionWithValue(OPTIO...
@Test public void processOptionsHeaderWithQuotas() { LinkedList<String> options = new LinkedList<String>(); options.add("-q"); options.add("-v"); options.add("dummy"); PrintStream out = mock(PrintStream.class); Count count = new Count(); count.out = out; count.processOptions(options...
public Order getOrderById(Long orderId) throws RestClientException { return getOrderByIdWithHttpInfo(orderId).getBody(); }
@Test public void getOrderByIdTest() { Long orderId = null; Order response = api.getOrderById(orderId); // TODO: test validations }
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by( PredicateT predicate) { return new Filter<>(predicate); }
@Test @Category(NeedsRunner.class) public void testFilterByPredicate() { PCollection<Integer> output = p.apply(Create.of(1, 2, 3, 4, 5, 6, 7)).apply(Filter.by(new EvenFn())); PAssert.that(output).containsInAnyOrder(2, 4, 6); p.run(); }
@Override public Collection<V> range(long startTimestamp, long endTimestamp, int limit) { return get(rangeAsync(startTimestamp, endTimestamp, limit)); }
@Test public void testRange() throws InterruptedException { RTimeSeries<String, Object> t = redisson.getTimeSeries("test"); t.add(1, "10"); t.add(2, "10"); t.add(3, "30"); t.add(4, "40"); assertThat(t.range(1, 4, 2)).containsExactly("10", "10"); assertThat(t....
@Override public Reiterator<Object> get(int tag) { return new SubIterator(tag); }
@Test public void testEmpties() { TaggedReiteratorList iter = create( new String[] {}, new String[] {"a", "b", "c"}, new String[] {}, new String[] {}, new String[] {"d"}); assertEquals(iter.get(2) /*empty*/); assertEquals(iter.get(1), "a"...
public static DataMap dataSchemaToDataMap(NamedDataSchema schema) { String inputSchemaAsString = schema.toString(); try { JacksonDataCodec codec = new JacksonDataCodec(); DataMap schemaAsDataMap = codec.stringToMap(inputSchemaAsString); return schemaAsDataMap; } catch (IOExceptio...
@Test public void testConvertDataSchemaToDataMap() throws IOException { for (String good : goodInputs) { NamedDataSchema dataSchema = (NamedDataSchema) TestUtil.dataSchemaFromString(good); DataMap mapFromSchema = Conversions.dataSchemaToDataMap(dataSchema); DataMap mapFromString = TestUti...
public static Labels fromResource(HasMetadata resource) { Map<String, String> additionalLabels = resource.getMetadata().getLabels(); if (additionalLabels != null) { additionalLabels = additionalLabels .entrySet() .stream() .filter(entryset -> ...
@Test public void testFromResourceWithoutLabels() { Kafka kafka = new KafkaBuilder() .withNewMetadata() .withName("my-kafka") .endMetadata() .withNewSpec() .withNewZookeeper() ...
public void reverseReplace(TestElement el) throws InvalidVariableException { Collection<JMeterProperty> newProps = replaceValues(el.propertyIterator(), new ReplaceFunctionsWithStrings(masterFunction, variables)); setProperties(el, newProps); }
@Test public void testOverlappingMatches() throws Exception { TestPlan plan = new TestPlan(); plan.addParameter("longMatch", "servername"); plan.addParameter("shortMatch", ".+"); ValueReplacer replacer = new ValueReplacer(plan); TestElement element = new TestPlan(); e...
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory( final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration, final Configuration jobConfiguration, final Configuration clusterConfiguration, final boolean is...
@Test void testExponentialDelayStrategySpecifiedInClusterConfig() { final Configuration conf = new Configuration(); conf.set(RestartStrategyOptions.RESTART_STRATEGY, EXPONENTIAL_DELAY.getMainValue()); final RestartBackoffTimeStrategy.Factory factory = RestartBackoffTimeStrat...
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); DecimalColumnStatsDataInspector aggregateData = decimalInspectorFromStats(aggregateColStats); Dec...
@Test public void testMergeNonNullWithNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(Decimal.class) .low(DECIMAL_1) .high(DECIMAL_3) .numNulls(4) .numDVs(2) .hll(1, 3, 3) .kll(1, 3, 3) .build()); ColumnStati...
@Override public boolean shouldFire(TriggerStateMachine.TriggerContext context) throws Exception { return getRepeated(context).invokeShouldFire(context); }
@Test public void testShouldFire() throws Exception { setUp(FixedWindows.of(Duration.millis(10))); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); assertTrue(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); when(mockTrigger.shouldFire(Mockito.any())).thenR...
public static long hash64(byte[] data) { int len = data.length; if (len <= 32) { if (len <= 16) { return hashLen0to16(data); } else { return hashLen17to32(data); } } else if (len <= 64) { return hashLen33to64(data); } // For strings over 64 bytes we hash the end first, and then as we //...
@Test public void hash64Test() { long hv = CityHash.hash64(StrUtil.utf8Bytes("你")); assertEquals(-4296898700418225525L, hv); hv = CityHash.hash64(StrUtil.utf8Bytes("你好")); assertEquals(-4294276205456761303L, hv); hv = CityHash.hash64(StrUtil.utf8Bytes("见到你很高兴")); assertEquals(272351505337503793L, hv); ...
public SslPrincipalMapper(String sslPrincipalMappingRules) { this.rules = parseRules(splitRules(sslPrincipalMappingRules)); }
@Test public void testSslPrincipalMapper() throws Exception { String rules = String.join(", ", "RULE:^CN=(.*?),OU=ServiceUsers.*$/$1/L", "RULE:^CN=(.*?),OU=(.*?),O=(.*?),L=(.*?),ST=(.*?),C=(.*?)$/$1@$2/L", "RULE:^cn=(.*?),ou=(.*?),dc=(.*?),dc=(.*?)$/$1@$2/U", ...
@Override public WebhookDelivery call(Webhook webhook, WebhookPayload payload) { WebhookDelivery.Builder builder = new WebhookDelivery.Builder(); long startedAt = system.now(); builder .setAt(startedAt) .setPayload(payload) .setWebhook(webhook); try { HttpUrl url = HttpUrl.par...
@Test public void silently_catch_error_when_url_is_incorrect() { Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40), "my-webhook", "this_is_not_an_url", null); WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD); assertThat(delivery.getHtt...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindVarargWithList() { // Given: givenFunctions( function(EXPECTED, 0, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex .getFunction(ImmutableList.of(SqlArgument.of(SqlArray.of(SqlTypes.STRING)))); // Then: assertThat(fun.name(),...
@Override public void getConfig(CloudDataPlaneFilterConfig.Builder builder) { if (clientsLegacyMode) { builder.legacyMode(true); } else { var clientsCfg = clients.stream() .filter(c -> !c.certificates().isEmpty()) .map(x -> new CloudDat...
@Test public void it_generates_correct_config() throws IOException { Path certFile = securityFolder.resolve("foo.pem"); Element clusterElem = DomBuilderTest.parse( """ <container version='1.0'> <clients> <...
public static void extract(Path source, Path destination) throws IOException { extract(source, destination, false); }
@Test public void testExtract() throws URISyntaxException, IOException { Path source = Paths.get(Resources.getResource("core/extract.tar").toURI()); Path destination = temporaryFolder.getRoot().toPath(); TarExtractor.extract(source, destination); Assert.assertTrue(Files.exists(destination.resolve("fi...
public void logSubscriptionRemoval(final String channel, final int streamId, final long subscriptionId) { final int length = SIZE_OF_INT * 2 + SIZE_OF_LONG + channel.length(); final int captureLength = captureLength(length); final int encodedLength = encodedLength(captureLength); fi...
@Test void logSubscriptionRemoval() { final int recordOffset = align(131, ALIGNMENT); logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, recordOffset); final String uri = "uri"; final int streamId = 42; final long id = 19; final int captureLength = uri.length() + ...
public long betweenYear(boolean isReset) { final Calendar beginCal = DateUtil.calendar(begin); final Calendar endCal = DateUtil.calendar(end); int result = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR); if (false == isReset) { final int beginMonthBase0 = beginCal.get(Calendar.MONTH); final int ...
@Test public void betweenYearTest2() { Date start = DateUtil.parse("2000-02-29"); Date end = DateUtil.parse("2018-02-28"); long betweenYear = new DateBetween(start, end).betweenYear(false); assertEquals(18, betweenYear); }
@Override public HashSlotCursor8byteKey cursor() { return new Cursor(); }
@Test(expected = AssertionError.class) @RequireAssertEnabled public void testCursor_advance_whenDisposed() { HashSlotCursor8byteKey cursor = hsa.cursor(); hsa.dispose(); cursor.advance(); }
@Override public synchronized UdfFactory ensureFunctionFactory(final UdfFactory factory) { validateFunctionName(factory.getName()); final String functionName = factory.getName().toUpperCase(); if (udafs.containsKey(functionName)) { throw new KsqlException("UdfFactory already registered as aggregate...
@Test public void shouldNotThrowWhenEnsuringCompatibleUdfFactory() { // Given: functionRegistry.ensureFunctionFactory(udfFactory); // When: functionRegistry.ensureFunctionFactory(udfFactory); // Then: no exception thrown. }
public List<String> getDatacentersFor( InetAddress address, String continent, String country, Optional<String> subdivision ) { final int NUM_DATACENTERS = 3; if(this.isEmpty()) { return Collections.emptyList(); } List<String> dcsBySubnet = getDatacentersBySubnet(address...
@Test void testGetFastestDatacentersEmptySubnet() throws UnknownHostException { var v4address = Inet4Address.getByName("200.200.123.1"); var actual = basicTable.getDatacentersFor(v4address, "NA", "US", Optional.of("VA")); assertThat(actual).isEqualTo(List.of("datacenter-2", "datacenter-1")); }
@SuppressWarnings("checkstyle:HiddenField") public AwsCredentialsProvider credentialsProvider( String accessKeyId, String secretAccessKey, String sessionToken) { if (!Strings.isNullOrEmpty(accessKeyId) && !Strings.isNullOrEmpty(secretAccessKey)) { if (Strings.isNullOrEmpty(sessionToken)) { ret...
@Test public void testSessionCredentialsConfiguration() { // set access key id, secret access key, and session token AwsClientProperties awsClientProperties = new AwsClientProperties(); AwsCredentialsProvider credentialsProvider = awsClientProperties.credentialsProvider("key", "secret", "token"); ...
@Nonnull @Override public Result addChunk(ByteBuf buf, @Nullable SocketAddress remoteAddress) { if (!buf.isReadable(2)) { return new Result(null, false); } try { final IpfixParser.MessageDescription messageDescription = shallowParser.shallowParseMessage(buf); ...
@SuppressWarnings("unchecked") @Test public void ixFlowTest() throws IOException, URISyntaxException { final IpfixAggregator ipfixAggregator = new IpfixAggregator(); final Map<String, Object> configMap = getIxiaConfigmap(); final IpfixCodec codec = new IpfixCodec(new Configuration(config...
@Operation(summary = "Redirect transactionId from BVD") @GetMapping(value = {"/frontchannel/saml/v4/return_from_bvd", "/frontchannel/saml/v4/idp/return_from_bvd"}) public RedirectView redirectFromBvd(@RequestParam(value = "transactionId") String transactionId, @RequestParam(value = "status", required = false) B...
@Test void redirectFromBvdTest() throws SamlSessionException, UnsupportedEncodingException { String redirectUrl = "redirectUrl"; httpServletRequestMock.setRequestedSessionId("sessionId"); when(assertionConsumerServiceUrlServiceMock.generateRedirectUrl(any(), anyString(), anyString(), any(Bvd...
@Override public PositionOutputStream create() { if (!exists()) { return createOrOverwrite(); } else { throw new AlreadyExistsException("Location already exists: %s", uri()); } }
@Test public void testCreate() { OSSURI uri = randomURI(); int dataSize = 8; byte[] data = randomData(dataSize); writeOSSData(uri, data); OutputFile out = OSSOutputFile.fromLocation(ossClient, uri.location(), aliyunProperties); assertThatThrownBy(out::create) .isInstanceOf(AlreadyEx...
@Override public Num calculate(BarSeries series, Position position) { return getTradeCost(series, position, series.numOf(initialAmount)); }
@Test public void fixedCostWithOnePosition() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); Position position = new Position(); Num criterion; criterion = getCriterion(1000d, 0d, 0.75d).calculate(series, position); assertNumEquals(0d, crit...
public static Pod createPod( String name, String namespace, Labels labels, OwnerReference ownerReference, PodTemplate template, Map<String, String> defaultPodLabels, Map<String, String> podAnnotations, Affinity affinity, ...
@Test public void testCreatePodWithNullValuesAndNullTemplate() { Pod pod = WorkloadUtils.createPod( NAME, NAMESPACE, LABELS, OWNER_REFERENCE, null, Map.of("default-label", "default-value"), Map.o...
public int hash(JimfsPath path) { // Note: JimfsPath.equals() is implemented using the compare() method below; // equalityUsesCanonicalForm is taken into account there via the namesOrdering, which is set // at construction time. int hash = 31; hash = 31 * hash + getFileSystem().hashCode(); fina...
@Test public void testHash_usingDisplayForm() { PathService pathService = fakePathService(PathType.unix(), false); JimfsPath path1 = new JimfsPath(pathService, null, ImmutableList.of(Name.create("FOO", "foo"))); JimfsPath path2 = new JimfsPath(pathService, null, ImmutableList.of(Name.create("FOO", "FOO")...
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } ...
@Test public void testIllegalSpdyRstStreamFrameStatusCode() throws Exception { short type = 3; byte flags = 0; int length = 8; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; int statusCode = 0; // invalid status code ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SI...
public Certificate add(CvCertificate cert) { final Certificate db = Certificate.from(cert); if (repository.countByIssuerAndSubject(db.getIssuer(), db.getSubject()) > 0) { throw new ClientException(String.format( "Certificate of subject %s and issuer %s already exists", db.ge...
@Test public void shouldNotAddCertificateIfAlreadyExists() throws Exception { certificateRepo.save(loadCvCertificate("rdw/acc/cvca.cvcert", true)); ClientException thrown = assertThrows(ClientException.class, () -> service.add(readCvCertificate("rdw/acc/cvca.cvcert"))); assertEquals("SSSSSS...
public static String getString(long date, String format) { Date d = new Date(date); return getString(d, format); }
@Test public void getString_dateSignature() throws ParseException { String expectedDate = "15/05/2012"; String format = "dd/MM/yyyy"; Date date = new SimpleDateFormat(format).parse(expectedDate); assertEquals(expectedDate, DateUtils.getString(date, format)); }
@Override public String toString() { if (str == null) { str = this.ip + ":" + this.port; } return str; }
@Test public void testToStringReset() { final Endpoint ep = new Endpoint("192.168.1.1", 8080); assertEquals("192.168.1.1:8080", ep.toString()); assertEquals("192.168.1.1:8080", ep.toString()); }
static void populateSchemaFromListOfRanges(Schema toPopulate, List<RangeNode> ranges) { Range range = consolidateRanges(ranges); if (range != null) { if (range.getLowEndPoint() != null) { if (range.getLowEndPoint() instanceof BigDecimal bigDecimal) { toPop...
@Test void evaluateUnaryTestsForDateRange() { List<LocalDate> expectedDates = Arrays.asList(LocalDate.of(2022, 1, 1), LocalDate.of(2024, 1, 1)); List<String> formattedDates = expectedDates.stream() .map(toFormat -> String.format("@\"%s-0%s-0%s\"", toFormat.getYear(), toFormat.getMont...
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@Test void testInterface() { MapFunction<String, Boolean> mapInterface = new MapFunction<String, Boolean>() { private static final long serialVersionUID = 1L; @Override public Boolean map(String record) throws Exception { ...
public void doesNotMatch(@Nullable String regex) { checkNotNull(regex); if (actual == null) { failWithActual("expected a string that does not match", regex); } else if (actual.matches(regex)) { failWithActual("expected not to match", regex); } }
@Test public void stringDoesNotMatchStringWithFail() { expectFailureWhenTestingThat("abcaaadev").doesNotMatch(".*aaa.*"); assertFailureValue("expected not to match", ".*aaa.*"); }
public final void isNotSameInstanceAs(@Nullable Object unexpected) { if (actual == unexpected) { /* * We use actualCustomStringRepresentation() because it might be overridden to be better than * actual.toString()/unexpected.toString(). */ failWithoutActual( fact("expected ...
@Test public void isNotSameInstanceAsWithObjects() { Object a = new Object(); Object b = new Object(); assertThat(a).isNotSameInstanceAs(b); }
@Override public void execute(ComputationStep.Context context) { DuplicationVisitor visitor = new DuplicationVisitor(); new DepthTraversalTypeAwareCrawler(visitor).visit(treeRootHolder.getReportTreeRoot()); context.getStatistics().add("duplications", visitor.count); }
@Test public void loads_never_consider_originals_from_batch_on_same_lines_as_the_equals() { reportReader.putDuplications( FILE_2_REF, createDuplication( singleLineTextRange(LINE), createInnerDuplicate(LINE + 1), createInnerDuplicate(LINE + 2), createInProjectDuplicate(FILE_1_REF, LINE ...
@Override public long getDelay() { return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L); }
@Test public void getDelay_returnNumberIfConfigEmpty() { long delay = underTest.getDelay(); assertThat(delay).isPositive(); }
@Override public Mono<Void> deleteBatchAsync(List<String> strings, DeleteRecordOptions options) { return Mono.fromRunnable(() -> { Map<String, Record> collection = getCollection(); strings.forEach(collection::remove); }); }
@Test public void deleteBatchAsync() { List<Hotel> hotels = getHotels(); recordCollection.upsertBatchAsync(hotels, null).block(); List<String> keys = hotels.stream().map(Hotel::getId).collect(Collectors.toList()); recordCollection.deleteBatchAsync(keys, null).block(); for (...
public static boolean containsMessage(@Nullable Throwable exception, String message) { if (exception == null) { return false; } if (exception.getMessage() != null && exception.getMessage().contains(message)) { return true; } return containsMessage(exception.getCause(), message); }
@Test public void testContainsNegativeWithNested() { assertThat( containsMessage( new IllegalStateException( "There is a bad state in the client", new IllegalArgumentException("RESOURCE_EXHAUSTED: Quota issues")), "401 Unauthorize...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 1 && "get".equals(methodName)) { return field((SelString) args[0]); } else if (extension != null) { return extension.call(methodName, args); } throw new UnsupportedOperationException( type() ...
@Test(expected = UnsupportedOperationException.class) public void testInvalidCallGet() { params.call("get", new SelType[] {}); }
public static <R> R callStaticMethod( ClassLoader classLoader, String fullyQualifiedClassName, String methodName, ClassParameter<?>... classParameters) { Class<?> clazz = loadClass(classLoader, fullyQualifiedClassName); return callStaticMethod(clazz, methodName, classParameters); }
@Test public void callStaticMethodReflectively_rethrowsError() { try { ReflectionHelpers.callStaticMethod(ExampleDescendant.class, "staticThrowError"); fail("Expected exception not thrown"); } catch (RuntimeException e) { throw new RuntimeException("Incorrect exception thrown", e); } cat...
@Override public long write(Sample sample) { Validate.validState(writer != null, "No writer set! Call setWriter() first!"); StringBuilder row = new StringBuilder(); char[] specials = new char[] { separator, CSVSaveService.QUOTING_CHAR, CharUtils.CR, CharUtils.LF }; fo...
@Test public void testWriteWithoutSample() throws Exception { try (Writer writer = new StringWriter(); CsvSampleWriter csvWriter = new CsvSampleWriter(writer, metadata)) { try { csvWriter.write(null); fail("NPE expected"); } catch (NullPoi...
@Override public void writeFiltered(List<FilteredMessage> filteredMessages) throws Exception { final var messages = filteredMessages.stream() .filter(message -> !message.destinations().get(FILTER_KEY).isEmpty()) .toList(); writes.mark(messages.size()); ignore...
@Test public void writeFiltered() throws Exception { final List<Message> messageList = buildMessages(2); output.writeFiltered(List.of( // The first message should not be written to the output because the output's filter key is not included. DefaultFilteredMessage.for...
public boolean isSlim() { return (hasTransparencyRelative(50, 16, 2, 4) || hasTransparencyRelative(54, 20, 2, 12) || hasTransparencyRelative(42, 48, 2, 4) || hasTransparencyRelative(46, 52, 2, 12)) || (isAreaBlackRelative(50, 16, 2, 4) && ...
@Test @EnabledIf("org.jackhuang.hmcl.JavaFXLauncher#isStarted") public void testIsSlim() throws Exception { String[] names = {"alex", "ari", "efe", "kai", "makena", "noor", "steve", "sunny", "zuri"}; for (String skin : names) { assertTrue(getSkin(skin, true).isSlim()); a...
public ControllerResult<Void> cleanBrokerData(final CleanControllerBrokerDataRequestHeader requestHeader, final BrokerValidPredicate validPredicate) { final ControllerResult<Void> result = new ControllerResult<>(); final String clusterName = requestHeader.getClusterName(); final String ...
@Test public void testCleanBrokerData() { mockMetaData(); CleanControllerBrokerDataRequestHeader header1 = new CleanControllerBrokerDataRequestHeader(DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, "1"); ControllerResult<Void> result1 = this.replicasInfoManager.cleanBrokerData(header1, (cluster, ...
public static TimeLock ofTimestamp(Instant time) { long secs = time.getEpochSecond(); if (secs < THRESHOLD) throw new IllegalArgumentException("timestamp too low: " + secs); return new TimeLock(secs); }
@Test(expected = IllegalArgumentException.class) public void ofTimestamp_tooLow() { LockTime.ofTimestamp(Instant.EPOCH.plus(365, ChronoUnit.DAYS)); }
@Override public boolean accept(final Path file, final Local local, final TransferStatus parent) throws BackgroundException { if(local.isFile()) { if(local.exists()) { // Read remote attributes final PathAttributes attributes = attribute.find(file); ...
@Test public void testAcceptDirectory() throws Exception { ResumeFilter f = new ResumeFilter(new DisabledDownloadSymlinkResolver(), new NullSession(new Host(new TestProtocol()))); Path p = new Path("a", EnumSet.of(Path.Type.directory)); assertTrue(f.accept(p, new NullLocal("d", "a") { ...
public boolean containsKey(final long key) { return get(key) != missingValue; }
@Test public void shouldNotContainKeyOfAMissingKey() { assertFalse(map.containsKey(1L)); }
@Override public DistroData getDatumSnapshot(String targetServer) { Member member = memberManager.find(targetServer); if (checkTargetServerStatusUnhealthy(member)) { throw new DistroException( String.format("[DISTRO] Cancel get snapshot caused by target server %s unhe...
@Test void testGetDatumSnapshotFailure() throws NacosException { assertThrows(DistroException.class, () -> { when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); ...
@Nullable public String ensureUser(String userName, String password, String firstName, String lastName, String email, Set<String> expectedRoles) { return ensureUser(userName, password, firstName, lastName, email, expectedRoles, false); }
@Test public void ensureUserWithoutExpectedRoles() throws Exception { final Permissions permissions = new Permissions(ImmutableSet.of()); final User existingUser = newUser(permissions); existingUser.setName("test-user"); existingUser.setFirstLastFullNames("Test", "User"); ex...
@Override public int getType() { checkState(); return TYPE_FORWARD_ONLY; }
@Test void assertGetType() { assertThat(actualResultSet.getType(), is(ResultSet.TYPE_FORWARD_ONLY)); }
public static void main(String[] argv) throws Throwable { Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler()); int nRet = 0; // usage: $0 user appId locId host port app_log_dir user_dir [user_dir]* // let $x = $x/usercache for $local.dir // MKDIR $x/$user/appcache/$appid ...
@Test public void testMain() throws Exception { ContainerLocalizerWrapper wrapper = new ContainerLocalizerWrapper(); ContainerLocalizer localizer = wrapper.setupContainerLocalizerForTest(); Random random = wrapper.random; List<Path> localDirs = wrapper.localDirs; Path tokenPath = wrapper.t...
@Override public List<Map<String, String>> taskConfigs(int maxTasks) { if (knownConsumerGroups == null) { // If knownConsumerGroup is null, it means the initial loading has not finished. // An exception should be thrown to trigger the retry behavior in the framework. log....
@Test public void testReplicationDisabled() { // disable the replication MirrorCheckpointConfig config = new MirrorCheckpointConfig(makeProps("enabled", "false")); Set<String> knownConsumerGroups = new HashSet<>(); knownConsumerGroups.add(CONSUMER_GROUP); // MirrorCheckpoint...
public static SortOrder buildSortOrder(Table table) { return buildSortOrder(table.schema(), table.spec(), table.sortOrder()); }
@Test public void testSortOrderClusteringAllPartitionFields() { PartitionSpec spec = PartitionSpec.builderFor(SCHEMA).day("ts").identity("category").build(); SortOrder order = SortOrder.builderFor(SCHEMA) .withOrderId(1) .asc(Expressions.day("ts")) .asc("category") ...
public List<ResContainer> makeResourcesXml(JadxArgs args) { Map<String, ICodeWriter> contMap = new HashMap<>(); for (ResourceEntry ri : resStorage.getResources()) { if (SKIP_RES_TYPES.contains(ri.getTypeName())) { continue; } String fn = getFileName(ri); ICodeWriter cw = contMap.get(fn); if (cw =...
@Test void testStringFormattedFalse() { ResourceStorage resStorage = new ResourceStorage(); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "string", "app_name", ""); re.setSimpleValue(new RawValue(3, 0)); re.setNamedValues(Lists.list()); resStorage.add(re); BinaryXMLStrings strings = new...
List<AlternativeInfo> calcAlternatives(final int s, final int t) { // First, do a regular bidirectional route search checkAlreadyRun(); init(s, 0, t, 0); runAlgo(); final Path bestPath = extractPath(); if (!bestPath.isFound()) { return Collections.emptyList();...
@Test public void testRelaxMaximumStretch() { BaseGraph g = createTestGraph(em); PMap hints = new PMap(); hints.putObject("alternative_route.max_weight_factor", 4); hints.putObject("alternative_route.local_optimality_factor", 0.5); hints.putObject("alternative_route.max_paths...
public static <T extends ScanTask> List<ScanTaskGroup<T>> planTaskGroups( List<T> tasks, long splitSize, int lookback, long openFileCost) { return Lists.newArrayList( planTaskGroups(CloseableIterable.withNoopClose(tasks), splitSize, lookback, openFileCost)); }
@Test public void testTaskGroupPlanningByPartition() { // When all files belong to the same partition, we should combine them together as long as the // total file size is <= split size List<PartitionScanTask> tasks = ImmutableList.of( taskWithPartition(SPEC1, PARTITION1, 64), ...
public long getClientExpiredTime() { return clientExpiredTime; }
@Test void testInitConfigFormEnv() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { mockEnvironment.setProperty(ClientConstants.CLIENT_EXPIRED_TIME_CONFIG_KEY, String.valueOf(EXPIRED_TIME)); Constructor<ClientConfig> declaredConstructor = Clie...
@Override public Map<String, String> getMetadata(final Path file) throws BackgroundException { try { return new GoogleStorageAttributesFinderFeature(session).find(file).getMetadata(); } catch(NotfoundException e) { if(file.isDirectory()) { // No placeh...
@Test public void testGetMetadataBucket() throws Exception { final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Map<String, String> metadata = new GoogleStorageMetadataFeature(session).getMetadata(bucket); assertTrue(metadata.isEmpty()...
private WorkflowRun getRun() { return PipelineRunImpl.findRun(runExternalizableId); }
@Test public void getRun_EventuallyFound() throws Exception { try (MockedStatic<QueueUtil> queueUtilMockedStatic = Mockito.mockStatic(QueueUtil.class)) { Mockito.when(QueueUtil.getRun(job, 1)).thenReturn(null).thenReturn(null).thenReturn(null).thenReturn(run); WorkflowRun workflowRu...
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { var triggers = annotations.stream() .filter(te -> { for (var trigger : KoraSchedulingAnnotationProcessor.triggers) { if (te.getQualifiedName().contentEquals(t...
@Test void testScheduledJdkOnceTest() throws Exception { process(ScheduledJdkOnceTest.class); }
void push(SelType obj) { stack[++top] = obj; }
@Test public void testPush() { assertTrue(state.isStackEmpty()); state.push(SelString.of("foo")); SelType res = state.readWithOffset(0); assertEquals("STRING: foo", res.type() + ": " + res); }
private IcebergTimeObjectInspector() { super(TypeInfoFactory.stringTypeInfo); }
@Test public void testIcebergTimeObjectInspector() { IcebergTimeObjectInspector oi = IcebergTimeObjectInspector.get(); assertThat(oi.getCategory()).isEqualTo(ObjectInspector.Category.PRIMITIVE); assertThat(oi.getPrimitiveCategory()) .isEqualTo(PrimitiveObjectInspector.PrimitiveCategory.STRING); ...
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldAnonymizeUDFQueriesCorrectly() { final String output = anon.anonymize("CREATE STREAM OUTPUT AS SELECT ID, " + "REDUCE(numbers, 2, (s, x) => s + x) AS reduce FROM test;"); Approvals.verify(output); }
public String generateRedirectUrl(String artifact, String transactionId, String sessionId, BvdStatus status) throws SamlSessionException, UnsupportedEncodingException { final var samlSession = findSamlSessionByArtifactOrTransactionId(artifact, transactionId); if (CANCELLED.equals(status)) s...
@Test void redirectWithIncorrectSession() { when(samlSessionRepositoryMock.findByArtifact(anyString())).thenReturn(Optional.empty()); Exception exception = assertThrows(SamlSessionException.class, () -> assertionConsumerServiceUrlService.generateRedirectUrl("SSSSSSSSSSSSSSSSSSSSSSSS...
public static DependencyVersion parseVersion(String text) { return parseVersion(text, false); }
@Test public void testParseVersion_String_boolean() { //cpe:/a:playframework:play_framework:2.1.1:rc1-2.9.x-backport String text = "2.1.1.rc1.2.9.x-backport"; boolean firstMatchOnly = false; DependencyVersion expResult; DependencyVersion result = DependencyVersionUtil.parseVe...
public static String getJsonToSave(@Nullable final List<Tab> tabList) { final JsonStringWriter jsonWriter = JsonWriter.string(); jsonWriter.object(); jsonWriter.array(JSON_TABS_ARRAY_KEY); if (tabList != null) { for (final Tab tab : tabList) { tab.writeJsonOn...
@Test public void testEmptyAndNullSave() throws JsonParserException { final List<Tab> emptyList = Collections.emptyList(); String returnedJson = TabsJsonHelper.getJsonToSave(emptyList); assertTrue(isTabsArrayEmpty(returnedJson)); final List<Tab> nullList = null; returnedJson...
@Nonnull @Override public Result addChunk(ByteBuf buffer) { final byte[] readable = new byte[buffer.readableBytes()]; buffer.readBytes(readable, buffer.readerIndex(), buffer.readableBytes()); final GELFMessage msg = new GELFMessage(readable); final ByteBuf aggregatedBuffer; ...
@Test public void missingChunk() { final DateTime initialTime = new DateTime(2014, 1, 1, 1, 59, 59, 0, DateTimeZone.UTC); final InstantMillisProvider clock = new InstantMillisProvider(initialTime); DateTimeUtils.setCurrentMillisProvider(clock); // we don't want the clean up task to ...
public static <K, InputT, AccumT> ParDoFn create( PipelineOptions options, KvCoder<K, ?> inputElementCoder, @Nullable CloudObject cloudUserFn, @Nullable List<SideInputInfo> sideInputInfos, List<Receiver> receivers, DataflowExecutionContext<?> executionContext, DataflowOperation...
@Test public void testPartialGroupByKeyWithCombiner() throws Exception { Coder keyCoder = StringUtf8Coder.of(); Coder valueCoder = BigEndianIntegerCoder.of(); TestOutputReceiver receiver = new TestOutputReceiver( new ElementByteSizeObservableCoder( WindowedValue.getVal...
static boolean areAllReplicasInSync(PartitionInfo partitionInfo) { return Arrays.asList(partitionInfo.inSyncReplicas()).containsAll(Arrays.asList(partitionInfo.replicas())); }
@Test public void testAreAllReplicasInSync() { // Verify: If isr is the same as replicas, all replicas are in-sync Node[] replicas = new Node[2]; replicas[0] = NODE_0; replicas[1] = NODE_1; Node[] isr = new Node[2]; isr[0] = NODE_0; isr[1] = NODE_1; PartitionInfo partitionInfo = new P...
@Override public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return join(otherStream, toValueJoinerWithKey(joiner), w...
@SuppressWarnings("deprecation") @Test public void shouldNotAllowNullStreamJoinedOnJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join( testStream, MockValueJoiner.TOSTRING_JOINER, ...
public static ILogger getLogger(@Nonnull Class<?> clazz) { checkNotNull(clazz, "class must not be null"); return getLoggerInternal(clazz.getName()); }
@Test public void getLogger_whenNone_thenReturnNoLogger() { isolatedLoggingRule.setLoggingType(LOGGING_TYPE_NONE); assertInstanceOf(NoLogFactory.NoLogger.class, Logger.getLogger(getClass())); }
UriEndpoint createUriEndpoint(String url, boolean isWs) { return createUriEndpoint(url, isWs, connectAddress); }
@Test void createUriEndpointRelative() { String test1 = this.builder.build() .createUriEndpoint("/foo", false) .toExternalForm(); String test2 = this.builder.build() .createUriEndpoint("/foo", true) .toExternalForm(); assertThat(test1).isEqualTo("http://localhost/foo"); assertThat(test2).isEqu...
public static GenericData get() { return INSTANCE; }
@Test void recordGetFieldDoesntExist() throws Exception { assertThrows(AvroRuntimeException.class, () -> { Schema schema = Schema.createRecord("test", "doc", "test", false, Collections.EMPTY_LIST); GenericData.Record record = new GenericData.Record(schema); record.get("does not exist"); }); ...
public void acquireReadLock(String key) { getLock(key).readLock().lock(); }
@Test public void shouldNotEnforceMutualExclusionOfReadLockForGivenName() throws InterruptedException { readWriteLock.acquireReadLock("foo"); new Thread(() -> { readWriteLock.acquireReadLock("foo"); numberOfLocks++; }).start(); Thread.sleep(1000); a...
@Override public LispNatLcafAddress getNatLcafAddress() { return natLcafAddress; }
@Test public void testConstruction() { DefaultLispInfoReply reply = (DefaultLispInfoReply) reply1; LispIpv4Address address = new LispIpv4Address(IpAddress.valueOf("192.168.1.4")); short msUdpPortNumber1 = 80; short etrUdpPortNumber1 = 100; LispIpv4Address globalEtrRlocAddre...
@VisibleForTesting public static SegmentSelectionResult processValidDocIdsMetadata(Map<String, String> taskConfigs, Map<String, SegmentZKMetadata> completedSegmentsMap, Map<String, List<ValidDocIdsMetadataInfo>> validDocIdsMetadataInfoMap) { double invalidRecordsThresholdPercent = Double.parseDouble( ...
@Test public void testProcessValidDocIdsMetadata() throws IOException { Map<String, String> compactionConfigs = getCompactionConfigs("1", "10"); String json = "{\"testTable__0\": [{\"totalValidDocs\": 50, \"totalInvalidDocs\": 50, " + "\"segmentName\": \"testTable__0\", \"totalDocs\": 100, \"seg...
@Nullable public static TraceContextOrSamplingFlags parseB3SingleFormat(CharSequence b3) { return parseB3SingleFormat(b3, 0, b3.length()); }
@Test void parseB3SingleFormat_middleOfString() { String input = "b3=" + traceIdHigh + traceId + "-" + spanId + ","; assertThat(parseB3SingleFormat(input, 3, input.length() - 1).context()) .isEqualToComparingFieldByField(TraceContext.newBuilder() .traceIdHigh(Long.parseUnsignedLong(traceIdHigh, 16...
@Override public Map<String, Object> load(String configKey) { if (targetFilePath != null) { try { Map<String, Object> raw = (Map<String, Object>) Utils.readYamlFile(targetFilePath); if (raw != null) { return (Map<String, Object>) raw.get(config...
@Test public void testValidFile() throws Exception { File temp = Files.createTempFile("FileLoader", ".yaml").toFile(); temp.deleteOnExit(); Map<String, Integer> testMap = new HashMap<>(); testMap.put("a", 1); testMap.put("b", 2); testMap.put("c", 3); testMap...
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception { return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM); }
@Test public void retriesEventuallySucceed() throws Exception { Mockito.when(mockCallable.call()) .thenThrow(new TimeoutException()) .thenThrow(new TimeoutException()) .thenThrow(new TimeoutException()) .thenReturn("success"); assertEq...
@SuppressWarnings("checkstyle:magicnumber") public static String getInternalBinaryName(byte[] classBytes) { try { ByteBuffer buffer = ByteBuffer.wrap(classBytes); buffer.order(ByteOrder.BIG_ENDIAN); // Skip magic number and major/minor versions buffer.positio...
@Test public void testAllConstantTagsReadable_whenReadingInternalBinaryName() { // To read an internal binary name, we need to read (and skip values for) all constant pool bytes // in the class file, so we need to make sure all 17 (as of JDK 21) are handled correctly byte[] classBytes = g...
public static Expression convert(Predicate[] predicates) { Expression expression = Expressions.alwaysTrue(); for (Predicate predicate : predicates) { Expression converted = convert(predicate); Preconditions.checkArgument( converted != null, "Cannot convert Spark predicate to Iceberg expres...
@SuppressWarnings("checkstyle:MethodLength") @Test public void testV2Filters() { Map<String, String> attrMap = Maps.newHashMap(); attrMap.put("id", "id"); attrMap.put("`i.d`", "i.d"); attrMap.put("`i``d`", "i`d"); attrMap.put("`d`.b.`dd```", "d.b.dd`"); attrMap.put("a.`aa```.c", "a.aa`.c"); ...
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> targetInvokers; if (routerConfig.isUseRequest...
@Test public void testGetMissMatchInvokers() { // initialize the routing rule RuleInitializationUtils.initFlowMatchRule(); List<Object> invokers = new ArrayList<>(); ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0"); invokers.add(invoker1); ApacheInvoker<O...
public JWTValidator validateDate() throws ValidateException { return validateDate(DateUtil.beginOfSecond(DateUtil.date())); }
@Test public void validateDateTest() { assertThrows(ValidateException.class, () -> { final JWT jwt = JWT.create() .setPayload("id", 123) .setPayload("username", "hutool") .setExpiresAt(DateUtil.parse("2021-10-13 09:59:00")); JWTValidator.of(jwt).validateDate(DateUtil.date()); }); }
@Override public ProviderGroup getProviderGroup(String groupName) { rLock.lock(); try { return RpcConstants.ADDRESS_DIRECT_GROUP.equals(groupName) ? directUrlGroup : registryGroup; } finally { rLock.unlock(); } }
@Test public void getProviders() throws Exception { SingleGroupAddressHolder addressHolder = new SingleGroupAddressHolder(null); Assert.assertTrue(ProviderHelper.isEmpty(addressHolder.getProviderGroup(null))); Assert.assertTrue(ProviderHelper.isEmpty(addressHolder.getProviderGroup(StringUtil...
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) { SinkConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!existingC...
@Test public void testMergeDifferentTimeout() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("timeoutMs", 102L); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( merged...
@Override public void judgeContinueToExecute(final SQLStatement statement) throws SQLException { ShardingSpherePreconditions.checkState(statement instanceof CommitStatement || statement instanceof RollbackStatement, () -> new SQLFeatureNotSupportedException("Current transaction is aborted, c...
@Test void assertJudgeContinueToExecuteWithRollbackStatement() { assertDoesNotThrow(() -> allowedSQLStatementHandler.judgeContinueToExecute(mock(RollbackStatement.class))); }
public static HealthStateScope forMaterial(Material material) { return new HealthStateScope(ScopeType.MATERIAL, material.getAttributesForScope().toString()); }
@Test public void shouldHaveDifferentScopeWhenAutoUpdateHasChanged() { SvnMaterial mat = MaterialsMother.svnMaterial("url1"); HealthStateScope scope1 = HealthStateScope.forMaterial(mat); mat.setAutoUpdate(false); HealthStateScope scope2 = HealthStateScope.forMaterial(mat); as...
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof JobMeta ) ) { return feedback; } JobMeta jobMeta = (JobMeta) subject; String description = jobMeta.getDesc...
@Test public void testVerifyRule_EmptyDescription_DisabledRule() { JobHasDescriptionImportRule importRule = getImportRule( 10, false ); JobMeta jobMeta = new JobMeta(); jobMeta.setDescription( "" ); List<ImportValidationFeedback> feedbackList = importRule.verifyRule( null ); assertNotNull( feedb...
public List<StatisticsFile> statisticsFiles() { return statisticsFiles; }
@Test public void testParseStatisticsFiles() throws Exception { String data = readTableMetadataInputFile("TableMetadataStatisticsFiles.json"); TableMetadata parsed = TableMetadataParser.fromJson(data); assertThat(parsed.statisticsFiles()).hasSize(1); assertThat(parsed.statisticsFiles()) .hasSi...
public void onRequest(FilterRequestContext requestContext, RestLiFilterResponseContextFactory filterResponseContextFactory) { // Initiate the filter chain iterator. The RestLiCallback will be passed to the method invoker at the end of the // filter chain. _filterChainIterator.onReq...
@SuppressWarnings("unchecked") @Test public void testFilterInvocationRequestErrorThrowsError() throws Exception { _restLiFilterChain = new RestLiFilterChain(Arrays.asList(_filters), _mockFilterChainDispatcher, _mockFilterChainCallback); _filters[1] = new CountFilterRequestErrorThrowsError(); w...
@Override public boolean supportsResultSetHoldability(final int holdability) { return false; }
@Test void assertSupportsResultSetHoldability() { assertFalse(metaData.supportsResultSetHoldability(0)); }
public static Logger empty() { return EMPTY_LOGGER; }
@Test public void emptyLoggerReturnsSameInstance() { Logger logger1 = Loggers.empty(); Logger logger2 = Loggers.empty(); assertThat(logger1, sameInstance(logger2)); }
public static InetSocketAddress getBindAddress(ServiceAttributeProvider service, AlluxioConfiguration conf) { int port = getPort(service, conf); assertValidPort(port); return new InetSocketAddress(getBindHost(service, conf), port); }
@Test public void testGetBindAddress() throws Exception { for (ServiceType service : ServiceType.values()) { if (service == ServiceType.JOB_MASTER_RAFT || service == ServiceType.MASTER_RAFT) { // Skip the raft services, which don't support separate bind and connect ports. continue; } ...
public void completeDefaults(Props props) { // init string properties for (Map.Entry<Object, Object> entry : defaults().entrySet()) { props.setDefault(entry.getKey().toString(), entry.getValue().toString()); } boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), false); if ...
@Test public void defaults_loads_properties_defaults_from_base_and_extensions() { Props p = new Props(new Properties()); when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of(new FakeExtension1(), new FakeExtension3())); processProperties.completeDefaults(p); assertThat(p.value("sonar.some.pr...
public CompletableFuture<Map<TopicIdPartition, ShareAcknowledgeResponseData.PartitionData>> releaseAcquiredRecords( String groupId, String memberId ) { log.trace("Release acquired records request for groupId: {}, memberId: {}", groupId, memberId); List<TopicIdPartition> topicIdPartit...
@Test public void testReleaseAcquiredRecordsWithIncorrectGroupId() { String groupId = "grp"; Uuid memberId = Uuid.randomUuid(); TopicIdPartition tp1 = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0)); ShareSessionCache cache = mock(ShareSessionCache.class); ...