focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static <T> RetryOperator<T> of(Retry retry) { return new RetryOperator<>(retry); }
@Test public void retryOnResultFailAfterMaxAttemptsWithExceptionUsingMono() { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(10)) .maxAttempts(3) .failAfterMaxAttempts(true) .build(...
@Override public CaseInsensitiveString getName() { if (((name == null) || isEmpty(name.toString())) && packageDefinition != null) { return new CaseInsensitiveString(getPackageDefinition().getRepository().getName() + "_" + packageDefinition.getName()); } else { return name; ...
@Test void shouldReturnNameAsNullIfPackageDefinitionIsNotSet() { assertThat(new PackageMaterial().getName()).isNull(); }
public static CustomWeighting.Parameters createWeightingParameters(CustomModel customModel, EncodedValueLookup lookup) { String key = customModel.toString(); Class<?> clazz = customModel.isInternal() ? INTERNAL_CACHE.get(key) : null; if (CACHE_SIZE > 0 && clazz == null) clazz = CACHE...
@Test public void testBrackets() { EdgeIteratorState primary = graph.edge(0, 1).setDistance(10).set(accessEnc, true, true). set(roadClassEnc, PRIMARY).set(avgSpeedEnc, 80); EdgeIteratorState secondary = graph.edge(0, 1).setDistance(10).set(accessEnc, true, true). set(...
public Double getProcessCpuLoad() { return getMXBeanValueAsDouble("ProcessCpuLoad"); }
@Test void ifOperatingSystemMXBeanReturnsNaNForProcessCpuLoadOnFirstCall_NegativeIsReturned() throws JMException { when(mBeanServer.getAttribute(objectName, "ProcessCpuLoad")).thenReturn(Double.NaN); assertThat(jobServerStats.getProcessCpuLoad()).isEqualTo(-1); }
public void dropExternalAnalyzeStatus(String tableUUID) { List<AnalyzeStatus> expireList = analyzeStatusMap.values().stream(). filter(status -> status instanceof ExternalAnalyzeStatus). filter(status -> ((ExternalAnalyzeStatus) status).getTableUUID().equals(tableUUID)). ...
@Test public void testDropExternalAnalyzeStatus() { Table table = connectContext.getGlobalStateMgr().getMetadataMgr().getTable("hive0", "partitioned_db", "t1"); AnalyzeMgr analyzeMgr = new AnalyzeMgr(); AnalyzeStatus analyzeStatus = new ExternalAnalyzeStatus(100, "hive0", "p...
public static JavaToSqlTypeConverter javaToSqlConverter() { return JAVA_TO_SQL_CONVERTER; }
@Test public void shouldConvertJavaStringToSqlString() { assertThat(javaToSqlConverter().toSqlType(String.class), is(SqlBaseType.STRING)); }
public boolean isFiller() { if(filler == null) return false; return !this.getFiller().equals(Filler.NONE); }
@Test void isFiller_true() { assertTrue(product.isFiller()); }
@Override public AnalyticsPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { Capabilities capabilities = capabilities(descriptor.id()); PluggableInstanceSettings pluginSettingsAndView = getPluginSettingsAndView(descriptor, extension); Image image = image(descriptor.id()); re...
@Test public void shouldBuildPluginInfoWithPluginSettingsConfiguration() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); PluginSettingsConfiguration value = new PluginSettingsConfiguration(); value.add(new PluginSettingsProperty("username", null).with(Pr...
public byte[] verifyAuthenticate(byte[] seed, byte[] result) throws RdaException { final SecureMessaging sm = new TDEASecureMessaging(seed, 0, 16, null); final byte[] calculatedMac = sm.mac( m -> m.update(result, 0, 32)); if (!CryptoUtils.compare(calculatedMac, result, 32)) { throw ...
@Test public void shouldThrowErrorIfAuthenticateMacIsDifferent() throws Exception { final CardVerifier verifier = verifier(null, null); final byte[] seed = Hex.decode("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); final byte[] result = Hex.decode("" + "SSSSSSSSSSSSSSSSSSSSSSSSS...
public Properties getAllPropertiesByTags(final List<String> tagList) { Properties prop = new Properties(); for (String tag : tagList) { prop.putAll(this.getAllPropertiesByTag(tag)); } return prop; }
@Test public void testGetAllPropertiesByTags() throws Exception { try{ out = new BufferedWriter(new FileWriter(CONFIG_CORE)); startConfig(); appendProperty("hadoop.tags.system", "YARN,HDFS,NAMENODE"); appendProperty("hadoop.tags.custom", "MYCUSTOMTAG"); appendPropertyByTag("dfs.cblo...
@Operation(summary = "createToken", description = "CREATE_TOKEN_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", schema = @Schema(implementation = int.class), required = true), @Parameter(name = "expireTime", description = "EXPIRE_TIME", schema = @Schema(implementat...
@Test public void testCreateToken() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userId", "4"); paramsMap.add("expireTime", "2019-12-18 00:00:00"); paramsMap.add("token", "607f5aeaaa2093dbdff5d5522ce00510"); MvcResul...
public static <InputT, OutputT> MapElements<InputT, OutputT> via( final InferableFunction<InputT, OutputT> fn) { return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor()); }
@Test @Category(ValidatesRunner.class) public void testPrimitiveDisplayData() { SimpleFunction<Integer, ?> mapFn = new SimpleFunction<Integer, Integer>() { @Override public Integer apply(Integer input) { return input; } }; MapElements<Integer, ?> ma...
@Subscribe public void handleDebugEvent(DebugEvent event) { LOG.debug("Received local debug event: {}", event); DebugEventHolder.setLocalDebugEvent(event); }
@Test public void testHandleDebugEvent() throws Exception { DebugEvent event = DebugEvent.create("Node ID", "Test"); assertThat(DebugEventHolder.getLocalDebugEvent()).isNull(); serverEventBus.post(event); assertThat(DebugEventHolder.getLocalDebugEvent()).isSameAs(event); }
@Override public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListener listener) throws Http2Exception { if (readError) { input.skipBytes(input.readableBytes()); return; } try { do { if (readingHeaders && !...
@Test public void failedWhenStreamWindowUpdateFrameWithZeroDelta() throws Http2Exception { final ByteBuf input = Unpooled.buffer(); try { writeFrameHeader(input, 4, WINDOW_UPDATE, new Http2Flags(), 1); input.writeInt(0); Http2Exception ex = assertThrows(Http2Excep...
static long sizeOf(Mutation m) { if (m.getOperation() == Mutation.Op.DELETE) { return sizeOf(m.getKeySet()); } long result = 0; for (Value v : m.getValues()) { switch (v.getType().getCode()) { case ARRAY: result += estimateArrayValue(v); break; case STRUCT...
@Test public void pgJsonb() throws Exception { Mutation empty = Mutation.newInsertOrUpdateBuilder("test").set("one").to(Value.pgJsonb("{}")).build(); Mutation nullValue = Mutation.newInsertOrUpdateBuilder("test") .set("one") .to(Value.pgJsonb((String) null)) ...
@Override public Space get() throws BackgroundException { try { final Path home = new DefaultHomeFinderService(session).find(); if(!home.isRoot()) { if(SDSQuotaFeature.unknown == home.attributes().getQuota()) { log.warn(String.format("No quota set ...
@Test public void testRoom() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume...
public void addNameChangedListener( NameChangedListener listener ) { if ( listener != null ) { nameChangedListeners.add( listener ); } }
@Test public void testAddNameChangedListener() { meta.fireNameChangedListeners( "a", "a" ); meta.fireNameChangedListeners( "a", "b" ); meta.addNameChangedListener( null ); meta.fireNameChangedListeners( "a", "b" ); NameChangedListener listener = mock( NameChangedListener.class ); meta.addNameC...
public static Optional<SingleRouteEngine> newInstance(final Collection<QualifiedTable> singleTables, final SQLStatement sqlStatement) { if (!singleTables.isEmpty()) { return Optional.of(new SingleStandardRouteEngine(singleTables, sqlStatement)); } // TODO move this logic to common ro...
@Test void assertNewInstanceWithEmptySingleTableNameAndOtherStatement() { assertFalse(SingleRouteEngineFactory.newInstance(Collections.emptyList(), mock(SQLStatement.class)).isPresent()); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetAnalyzerName() { assertEquals("MSBuild Project Analyzer", instance.getName()); }
public S loadFirstInstance() { load(); if (classList.size() == 0) { return null; } Class<? extends S> serviceClass = classList.get(0); S instance = createInstance(serviceClass); return instance; }
@Test public void testLoadFirstInstance() { ProcessorSlot slot = SpiLoader.of(ProcessorSlot.class).loadFirstInstance(); assertNotNull(slot); assertTrue(slot instanceof NodeSelectorSlot); SlotChainBuilder chainBuilder = SpiLoader.of(SlotChainBuilder.class).loadFirstInstance(); ...
public static Sessions withGapDuration(Duration gapDuration) { return new Sessions(gapDuration); }
@Test public void testConsecutive() throws Exception { Map<IntervalWindow, Set<String>> expected = new HashMap<>(); expected.put(new IntervalWindow(new Instant(1), new Instant(19)), set(1, 2, 5, 9)); expected.put(new IntervalWindow(new Instant(100), new Instant(111)), set(100, 101)); assertEquals( ...
@Udf(description = "Returns a new string encoded using the outputEncoding ") public String encode( @UdfParameter( description = "The source string. If null, then function returns null.") final String str, @UdfParameter( description = "The input encoding." + " If null, the...
@Test public void shouldEncodeAsciiToHex() { assertThat(udf.encode("Example!", "ascii", "hex"), is("4578616d706c6521")); assertThat(udf.encode("Plant trees", "ascii", "hex"), is("506c616e74207472656573")); assertThat(udf.encode("1 + 1 = 1", "ascii", "hex"), is("31202b2031203d2031")); assertThat(udf.en...
public boolean isAnonymous() { return anonymous; }
@Test public void isAnonymous() throws Exception { assertTrue( ActingPrincipal.ANONYMOUS.isAnonymous() ); assertFalse( new ActingPrincipal( "harold" ).isAnonymous() ); assertFalse( new ActingPrincipal( "" ).isAnonymous() ); }
public static WaitForOptions defaults() { return new WaitForOptions().setInterval(DEFAULT_INTERVAL).setTimeoutMs(NEVER); }
@Test public void defaults() { WaitForOptions options = WaitForOptions.defaults(); assertEquals(WaitForOptions.DEFAULT_INTERVAL, options.getInterval()); assertEquals(WaitForOptions.NEVER, options.getTimeoutMs()); }
@Override public void batchUnSubscribe(List<ConsumerConfig> configs) { for (ConsumerConfig config : configs) { unSubscribe(config); } }
@Test public void testBatchUnSubscribe() { ConsumerConfig<Object> config1 = new ConsumerConfig<>(); String direct1 = "2"; config1.setDirectUrl(direct1); ConsumerConfig<Object> config2 = new ConsumerConfig<>(); String direct2 = "1"; config2.setDirectUrl(direct2); ...
protected Credentials configureCredentials(AuthConfiguration auth) { if (null != auth.getCredentialType() && auth.getCredentialType().equalsIgnoreCase(AuthConfiguration.NT_CREDS)) { return new NTCredentials(auth.getUsername(), auth.getPassword().toCharArray(), auth.getHostname(), auth.getDomain());...
@Test void configureCredentialReturnsNTCredentialsForNTLMConfig() { assertThat(builder.configureCredentials(new AuthConfiguration("username", "password", "NTLM", "realm", "hostname", "domain", "NT"))) .isInstanceOfSatisfying(NTCredentials.class, credentials -> assertThat(credentials) ...
@Override public void close() { dataSource.close(); }
@Test void assertClose() { repository.close(); HikariDataSource hikariDataSource = mockedConstruction.constructed().get(0); verify(hikariDataSource).close(); }
public void validate(String clientId, String clientSecret, String workspace) { Token token = validateAccessToken(clientId, clientSecret); if (token.getScopes() == null || !token.getScopes().contains("pullrequest")) { LOG.info(MISSING_PULL_REQUEST_READ_PERMISSION + String.format(SCOPE, token.getScopes()))...
@Test public void nullErrorBodyIsSupported() throws IOException { OkHttpClient clientMock = mock(OkHttpClient.class); Call callMock = mock(Call.class); String url = "http://any.test/"; String message = "Unknown issue"; when(callMock.execute()).thenReturn(new Response.Builder() .request(new ...
@VisibleForTesting public static boolean isDateAfterOrSame( String date1, String date2 ) { return date2.compareTo( date1 ) >= 0; }
@Test public void isDateAfterOrSame_SameTest() { assertTrue( TransPreviewProgressDialog.isDateAfterOrSame( SAME_DATE_STR, SAME_DATE_STR ) ); }
public static void addBlockCacheCapacityMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMe...
@Test public void shouldAddBlockCacheCapacityMetric() { final String name = "block-cache-capacity"; final String description = "Capacity of the block cache in bytes"; runAndVerifyMutableMetric( name, description, () -> RocksDBMetrics.addBlockCacheCapacityM...
@Override public List<String> splitAndEvaluate() { return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : split(inlineExpression); }
@Test void assertEvaluateForSimpleString() { List<String> expected = TypedSPILoader.getService(InlineExpressionParser.class, "LITERAL", PropertiesBuilder.build( new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, " t_order_0, t_order_1 "))).splitAndEvaluate(); ...
@Override public void not() { get(notAsync()); }
@Test public void testNot() { RBitSet bs = redisson.getBitSet("testbitset"); bs.set(3); bs.set(5); bs.not(); assertThat(bs.toString()).isEqualTo("{0, 1, 2, 4, 6, 7}"); }
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 shouldChooseCorrectLambdaFunction() { // Given: givenFunctions( function(FIRST_FUNC, -1, GENERIC_MAP, LAMBDA_KEY_FUNCTION) ); givenFunctions( function(SECOND_FUNC, -1, GENERIC_MAP, LAMBDA_VALUE_FUNCTION) ); // When: final KsqlScalarFunction first_fun = ud...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, String.valueOf(Path.DELIMITER)); }
@Test public void testListEncodedCharacterFolderNonVersioned() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("us-east-1"); final Path placeholder = new GoogleStorageDirectoryFeature...
public static <E> E checkNotInstanceOf(Class type, E object, String errorMessage) { isNotNull(type, "type"); if (type.isInstance(object)) { throw new IllegalArgumentException(errorMessage); } return object; }
@Test public void test_checkNotInstanceOf_withNullObject() { Object value = checkNotInstanceOf(Integer.class, null, "argumentName"); assertNull(value); }
@Override public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException { return new Checksum(HashAlgorithm.md5, this.digest("MD5", this.normalize(in, status), status)); }
@Test public void testNormalize() throws Exception { assertEquals("a43c1b0aa53a0c908810c06ab1ff3967", new MD5ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()), new TransferStatus()).hash); assertEquals("a43c1b0aa53a0c908810c06ab1ff3967", ...
public static <F extends Future<Void>> Mono<Void> deferFuture(Supplier<F> deferredFuture) { return new DeferredFutureMono<>(deferredFuture); }
@Test void testDeferredFutureMonoImmediate() { ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE; Supplier<Future<Void>> promiseSupplier = () -> eventExecutor.newFailedFuture(new ClosedChannelException()); StepVerifier.create(FutureMono.deferFuture(promiseSupplier)) .expectErr...
public static List<Integer> asIntegerList(@Nonnull int[] array) { checkNotNull(array, "null array"); return new AbstractList<>() { @Override public Integer get(int index) { return array[index]; } @Override public int size() { ...
@Test public void testToIntegerList_whenEmpty() { List<Integer> result = asIntegerList(new int[0]); assertEquals(0, result.size()); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromEarliestSnapshotWithEmptyTable() throws Exception { ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_EARLIEST_SNAPSHOT) .build(); ContinuousSplitPlannerImpl splitPlanner = n...
@Override public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) { ScannerReport.LineCoverage reportCoverage = getNextLineCoverageIfMatchLine(lineBuilder.getLine()); if (reportCoverage != null) { processCoverage(lineBuilder, reportCoverage); coverage = null; } return Optio...
@Test public void does_not_set_deprecated_coverage_fields() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setHits(true) .setCoveredConditions(2) .build()).iterator()); DbFile...
public static Date getDate(Object date) { return getDate(date, Calendar.getInstance().getTime()); }
@Test @SuppressWarnings("UndefinedEquals") public void testGetDateObjectDateWithValidStringAndNullDefault() { Calendar cal = new GregorianCalendar(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, ...
@Override protected @UnknownKeyFor @NonNull @Initialized SchemaTransform from( JdbcReadSchemaTransformConfiguration configuration) { configuration.validate(); return new JdbcReadSchemaTransform(configuration); }
@Test public void testReadWithJdbcTypeSpecified() { JdbcReadSchemaTransformProvider provider = null; for (SchemaTransformProvider p : ServiceLoader.load(SchemaTransformProvider.class)) { if (p instanceof JdbcReadSchemaTransformProvider) { provider = (JdbcReadSchemaTransformProvider) p; b...
static String toDatabaseName(Namespace namespace, boolean skipNameValidation) { if (!skipNameValidation) { validateNamespace(namespace); } return namespace.level(0); }
@Test public void testToDatabaseName() { assertThat(IcebergToGlueConverter.toDatabaseName(Namespace.of("db"), false)).isEqualTo("db"); }
@Override public byte[] serialize() { byte[] payloadData = null; if (this.payload != null) { this.payload.setParent(this); payloadData = this.payload.serialize(); } int payloadLength = 0; if (payloadData != null) { payloadLength = payloadD...
@Test public void testSerialize() { Fragment frag = new Fragment(); frag.setNextHeader((byte) 0x11); frag.setFragmentOffset((short) 0x1f); frag.setMoreFragment((byte) 1); frag.setIdentification(0x1357); frag.setPayload(udp); assertArrayEquals(frag.serialize()...
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfigurati...
@Test public void testEvictionRemoveSegmented() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .memory().evictionStrategy(EvictionStrategy.REMOVE).size(1000) .clustering().cacheMode(CacheMode.DIST_ASYNC).build(); Object component = dataContainerFac...
public final BarcodeParameters getParams() { return params; }
@Test final void testConstructorWithSize() throws IOException { try (BarcodeDataFormat barcodeDataFormat = new BarcodeDataFormat(200, 250)) { this.checkParams(BarcodeParameters.IMAGE_TYPE, 200, 250, BarcodeParameters.FORMAT, barcodeDataFormat.getParams()); } }
public boolean hasAnyMethodHandlerAnnotation() { return !operationsWithHandlerAnnotation.isEmpty(); }
@Test public void testHandlerOnSyntheticProxy() { Object proxy = buildProxyObject(); BeanInfo info = new BeanInfo(context, proxy.getClass()); assertTrue(info.hasAnyMethodHandlerAnnotation()); }
public boolean is(T state, T... otherStates) { return EnumSet.of(state, otherStates).contains(currentState); }
@Test public void testIsInInitialState_whenCreated() { assertTrue(machine.is(State.A)); }
public List<ShenyuServiceInstance> getCopyInstances() { List<ShenyuServiceInstance> copy = new ArrayList<>(shenyuServiceInstances.size()); shenyuServiceInstances.forEach(instance -> { ShenyuServiceInstance cp = ShenyuServiceTransfer.INSTANCE.deepCopy(instance); copy.add(cp); ...
@Test public void getCopyInstances() { List<ShenyuServiceInstance> list = shenyuServiceInstanceLists.getCopyInstances(); Assertions.assertEquals(1, list.size()); }
public void markAsUnchanged(DefaultInputFile file) { if (isFeatureActive()) { if (file.status() != InputFile.Status.SAME) { LOG.error("File '{}' was marked as unchanged but its status is {}", file.getProjectRelativePath(), file.status()); } else { LOG.debug("File '{}' marked as unchanged...
@Test public void not_active_if_using_different_reference() { logTester.setLevel(Level.DEBUG); BranchConfiguration differentRefConfig = branchConfiguration("a", "b", false); UnchangedFilesHandler handler = new UnchangedFilesHandler(enabledConfig, differentRefConfig, executingSensorContext); assertThat...
@Override public void start() { // we request a split only if we did not get splits during the checkpoint restore if (getNumberOfCurrentlyAssignedSplits() == 0) { context.sendSplitRequest(); } }
@Test void testRequestSplitWhenNoSplitRestored() throws Exception { final TestingReaderContext context = new TestingReaderContext(); final FileSourceReader<String, FileSourceSplit> reader = createReader(context); reader.start(); reader.close(); assertThat(context.getNumSpli...
public final <K, V> void addSink(final String name, final String topic, final Serializer<K> keySerializer, final Serializer<V> valSerializer, final StreamPartitioner<? supe...
@Test public void testAddSinkWithWrongParent() { assertThrows(TopologyException.class, () -> builder.addSink("sink", "topic-2", null, null, null, "source")); }
public void assign(AssignType assignType, String name, String exp, boolean docString) { name = StringUtils.trimToEmpty(name); validateVariableName(name); // always validate when gherkin if (vars.containsKey(name)) { LOGGER.debug("over-writing existing variable '{}' with new value: {}...
@Test void testResponseShortCuts() { assign("response", "{ foo: 'bar' }"); matchEquals("response", "{ foo: 'bar' }"); matchEquals("$", "{ foo: 'bar' }"); matchEquals("response.foo", "'bar'"); matchEquals("$.foo", "'bar'"); assign("response", "<root><foo>bar</foo></roo...
public static boolean isValidScopeToken(String scopeToken) { return VALID_SCOPE_TOKEN.matcher(scopeToken).matches(); }
@Test public void testOAuthScopeTokenValidation() { // valid scope tokens are from ascii 0x21 to 0x7E, excluding 0x22 (") and 0x5C (\) // test characters that are outside of the ! to ~ range and the excluded characters, " and \ assertThat(OAuth2Util.isValidScopeToken("a\\b")) .as("Should reject sc...
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException { try { rep.saveDatabaseMetaStepAttribute( id_transformation, id_step, "id_connection", databaseMeta ); rep.saveStepAttribute( id_transformation, id_step, "schema", schema...
@Test public void testSaveRep() throws Exception { TableOutputMeta tableOutputMeta = new TableOutputMeta(); tableOutputMeta.loadXML( getTestNode(), databases, metaStore ); StringObjectId id_step = new StringObjectId( "stepid" ); StringObjectId id_transformation = new StringObjectId( "transid" ); R...
public OptExpression next() { // For logic scan to physical scan, we only need to match once if (isPatternWithoutChildren && groupExpressionIndex.get(0) > 0) { return null; } OptExpression expression; do { this.groupTraceKey = 0; // Match wit...
@Test public void testBinderDepth2Repeat1() { OptExpression expr1 = OptExpression.create(new MockOperator(OperatorType.LOGICAL_JOIN, 0), OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN, 1)), OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_...
public String multipleConditionsExample() { IamPolicy policy = IamPolicy.builder() .addStatement(b -> b .effect(IamEffect.ALLOW) .addAction("dynamodb:GetItem") ...
@Test @Tag("IntegrationTest") void multipleConditionsExample() { String jsonPolicy = examples.multipleConditionsExample(); logger.info(jsonPolicy); analyze(jsonPolicy, PolicyType.IDENTITY_POLICY); }
public static FlinkPod loadPodFromTemplateFile( FlinkKubeClient kubeClient, File podTemplateFile, String mainContainerName) { final KubernetesPod pod = kubeClient.loadPodFromTemplateFile(podTemplateFile); final List<Container> otherContainers = new ArrayList<>(); Container mainContai...
@Test void testLoadPodFromTemplateAndCheckMainContainer() { final FlinkPod flinkPod = KubernetesUtils.loadPodFromTemplateFile( flinkKubeClient, KubernetesPodTemplateTestUtils.getPodTemplateFile(), KubernetesPodTemplateTe...
abstract void execute(Admin admin, Namespace ns, PrintStream out) throws Exception;
@Test public void testNewBrokerAbortTransaction() throws Exception { TopicPartition topicPartition = new TopicPartition("foo", 5); long startOffset = 9173; long producerId = 12345L; short producerEpoch = 15; int coordinatorEpoch = 76; String[] args = new String[] { ...
public static String deepToString(Iterator<?> iter) { StringBuilder bld = new StringBuilder("["); String prefix = ""; while (iter.hasNext()) { Object object = iter.next(); bld.append(prefix); bld.append(object.toString()); prefix = ", "; } ...
@Test public void testDeepToString() { assertEquals("[1, 2, 3]", MessageUtil.deepToString(Arrays.asList(1, 2, 3).iterator())); assertEquals("[foo]", MessageUtil.deepToString(Collections.singletonList("foo").iterator())); }
public String getBaseUrl() { String url = config.get(SERVER_BASE_URL).orElse(""); if (isEmpty(url)) { url = computeBaseUrl(); } // Remove trailing slashes return StringUtils.removeEnd(url, "/"); }
@Test public void base_url_is_http_localhost_900_specified_context_when_context_is_set() { settings.setProperty(CONTEXT_PROPERTY, "sdsd"); assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000sdsd"); }
public boolean isAllAllowed() { return allAllowed; }
@Test public void testWildCardAccessControlList() throws Exception { AccessControlList acl; acl = new AccessControlList("*"); assertTrue(acl.isAllAllowed()); acl = new AccessControlList(" * "); assertTrue(acl.isAllAllowed()); acl = new AccessControlList(" *"); assertTrue(ac...
public static Field p(String fieldName) { return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName); }
@Test void contains_phrase_near_onear_equiv() { { String q1 = Q.p("f1").containsPhrase("p1", "p2", "p3") .build(); String q2 = Q.p("f1").containsPhrase(List.of("p1", "p2", "p3")) .build(); assertEquals(q1, "yql=select * from sources...
public String allowCrossAccountAccessExample() { IamPolicy policy = IamPolicy.builder() .addStatement(b -> b .effect(IamEffect.ALLOW) .addPrincipal(IamPrincipalType.AWS, "11112...
@Test @Tag("IntegrationTest") void allowCrossAccountAccessExample() { String policyJson = examples.allowCrossAccountAccessExample(); logger.info(policyJson); analyze(policyJson, PolicyType.RESOURCE_POLICY); }
@Override public RecordSet getRecordSet(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorSplit split, List<? extends ColumnHandle> columns) { PrometheusSplit prometheusSplit = (PrometheusSplit) split; ImmutableList.Builder<PrometheusColumnHandle> handles = Immuta...
@Test public void testGetRecordSet() { PrometheusRecordSetProvider recordSetProvider = new PrometheusRecordSetProvider(client); RecordSet recordSet = recordSetProvider.getRecordSet( PrometheusTransactionHandle.INSTANCE, SESSION, new PrometheusSplit...
@Override public double logp(int k) { if (k < 0) { return Double.NEGATIVE_INFINITY; } else { return k * Math.log(1 - p) + Math.log(p); } }
@Test public void testLogP() { System.out.println("logP"); GeometricDistribution instance = new GeometricDistribution(0.3); instance.rand(); assertEquals(Math.log(0.3), instance.logp(0), 1E-6); assertEquals(Math.log(0.21), instance.logp(1), 1E-6); assertEquals(Math.lo...
public FEELFnResult<Boolean> invoke(@ParameterName( "range" ) Range range, @ParameterName( "point" ) Comparable point) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { ret...
@Test void invokeParamRangeAndRange() { FunctionTestUtil.assertResult( finishedByFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ), ...
@Override public String getAcknowledgmentType() { return "AR"; }
@Test public void testGetAcknowledgmentType() { instance = new MllpApplicationRejectAcknowledgementException( HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertEquals("AR", instance.getAcknowledgmentType()); }
@Override public void selectInstances(Map<Integer, List<InstanceConfig>> poolToInstanceConfigsMap, InstancePartitions instancePartitions) { int numPools = poolToInstanceConfigsMap.size(); Preconditions.checkState(numPools != 0, "No pool qualified for selection"); int tableNameHash = Math.abs(_table...
@Test public void testSelectPoolsWhenExistingReplicaGroupMapsToMultiplePools() throws JsonProcessingException { // The "rg0-2" instance used to belong to Pool 1, but now it belongs to Pool 0. //@formatter:off String existingPartitionsJson = "{\n" + " \"instancePartitionsName\": \"0f97...
public static void populateGetCreatedLocalTransformationsMethod(final ClassOrInterfaceDeclaration toPopulate, final LocalTransformations localTransformations) { if (localTransformations != null) { BlockStmt createLocalTransformation...
@Test void populateGetCreatedLocalTransformationsMethod() throws IOException { org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.populateGetCreatedLocalTransformationsMethod(classOrInterfaceDeclaration, ...
public static void validateImageInDaemonConf(Map<String, Object> conf) { List<String> allowedImages = getAllowedImages(conf, true); if (allowedImages.isEmpty()) { LOG.debug("{} is not configured; skip image validation", DaemonConfig.STORM_OCI_ALLOWED_IMAGES); } else { Str...
@Test public void validateImageInDaemonConfTest() { Map<String, Object> conf = new HashMap<>(); List<String> allowedImages = new ArrayList<>(); allowedImages.add("storm/rhel7:dev_test"); allowedImages.add("storm/rhel7:dev_current"); conf.put(DaemonConfig.STORM_OCI_ALLOWED_IMA...
@Override public Map<String, String> getLabels(Properties properties) { LOGGER.info("DefaultLabelsCollectorManager get labels....."); Map<String, String> labels = getLabels(labelsCollectorsList, properties); LOGGER.info("DefaultLabelsCollectorManager get labels finished,labels :{}", labels);...
@Test void tagV2LabelsCollectorTest() { Properties properties = new Properties(); properties.put(Constants.APP_CONN_LABELS_KEY, "k1=v1,gray=properties_pre"); properties.put(Constants.CONFIG_GRAY_LABEL, "properties_after"); DefaultLabelsCollectorManager defaultLabelsCollectorManager =...
public List<String> split(String in) { final StringBuilder result = new StringBuilder(); final char[] chars = in.toCharArray(); for (int i = 0; i < chars.length; i++) { final char c = chars[i]; if (CHAR_OPERATORS.contains(String.valueOf(c))) { if (i < char...
@Test public void split4() { List<String> tokens = parser.split("a and b AND(((a>c AND b> d) OR (x = y )) ) OR t>u"); assertEquals(Arrays.asList("a", "and", "b", "AND", "(", "(", "(", "a", ">", "c", "AND", "b", ">", "d", ")", "OR", "(", "x", "=", "y", ")", ")", ")", "OR", "t", ">", "...
public T_IdKeyPair generateOmemoIdentityKeyPair() { return keyUtil().generateOmemoIdentityKeyPair(); }
@Test public void generateOmemoIdentityKeyPairDoesNotReturnNull() { assertNotNull(store.generateOmemoIdentityKeyPair()); }
@Override public boolean add(E e) { final int priorityLevel = e.getPriorityLevel(); // try offering to all queues. if (!offerQueues(priorityLevel, e, true)) { CallQueueOverflowException ex; if (serverFailOverEnabled) { // Signal clients to failover and try a separate server. e...
@Test public void testFairCallQueueMetrics() throws Exception { final String fcqMetrics = "ns.FairCallQueue"; Schedulable p0 = mockCall("a", 0); Schedulable p1 = mockCall("b", 1); assertGauge("FairCallQueueSize_p0", 0, getMetrics(fcqMetrics)); assertGauge("FairCallQueueSize_p1", 0, getMetrics(fcq...
public static boolean isServletRequestAuthenticatorInstanceOf(Class<? extends ServletRequestAuthenticator> clazz) { final AuthCheckFilter instance = getInstance(); if (instance == null) { // We've not yet been instantiated return false; } return servletRequestAuth...
@Test public void willReturnTrueIfTheCorrectServletRequestAuthenticatorIsConfigured() { new AuthCheckFilter(adminManager, loginLimitManager); AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(NormalUserServletAuthenticatorClass.class); assertThat(AuthCheckFilter.isServletRequestAuthen...
public void saveV2(ImageWriter imageWriter) throws IOException { try { // 1 json for myself,1 json for number of users, 2 json for each user(kv) // 1 json for number of roles, 2 json for each role(kv) final int cnt = 1 + 1 + userToPrivilegeCollection.size() * 2 ...
@Test public void testWontSavePrivCollForBuiltInRole() throws Exception { GlobalStateMgr masterGlobalStateMgr = ctx.getGlobalStateMgr(); AuthorizationMgr authorizationMgr = masterGlobalStateMgr.getAuthorizationMgr(); UtFrameUtils.PseudoJournalReplayer.resetFollowerJournalQueue(); Ut...
public static boolean equals(double num1, double num2) { return Double.doubleToLongBits(num1) == Double.doubleToLongBits(num2); }
@Test public void equalsTest() { assertTrue(NumberUtil.equals(new BigDecimal("0.00"), BigDecimal.ZERO)); }
@Override public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) { StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES"); String[] queryParams = null; switch (scope.type()) { case ROOT: // account-level listing baseQuery.append(" IN ACCOUNT"); ...
@SuppressWarnings("unchecked") @Test public void testListIcebergTablesInDatabase() throws SQLException { when(mockResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); when(mockResultSet.getString("database_name")) .thenReturn("DB_1") .thenReturn("DB_1") ...
public void seek(long pos) throws IOException { if (input instanceof RandomAccessFile) { ((RandomAccessFile) input).seek(pos); } else if (input instanceof DataInputStream) { throw new UnsupportedOperationException("Can not seek on Hollow Blob Input of type DataInputStream"); ...
@Test public void testSeek() throws IOException { try (HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob)) { inStream.seek(3); fail(); } catch (UnsupportedOperationException e) { // pass } catch (Exception e) { ...
@InvokeOnHeader(Web3jConstants.ETH_GET_UNCLE_BY_BLOCK_HASH_AND_INDEX) void ethGetUncleByBlockHashAndIndex(Message message) throws IOException { String blockHash = message.getHeader(Web3jConstants.BLOCK_HASH, configuration::getBlockHash, String.class); BigInteger uncleIndex = message.getHeader(Web3jC...
@Test public void ethGetUncleByBlockHashAndIndexTest() throws Exception { EthBlock response = Mockito.mock(EthBlock.class); Mockito.when(mockWeb3j.ethGetUncleByBlockHashAndIndex(any(), any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(respon...
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { ret...
@Test void invokeParamRangeAndRange() { FunctionTestUtil.assertResult( duringFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ), ...
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { ObjectUtil.checkNotNull(command, "command"); ObjectUtil.checkNotNull(unit, "unit"); if (initialDelay < 0) { throw new IllegalArgumentException( ...
@Test public void testScheduleAtFixedRateRunnableZero() { final TestScheduledEventExecutor executor = new TestScheduledEventExecutor(); assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { executor.scheduleAtFixedRa...
@Operation(summary = "countDefinitionByUser", description = "COUNT_PROCESS_DEFINITION_BY_USER_NOTES") @Parameters({ @Parameter(name = "projectCode", description = "PROJECT_CODE", schema = @Schema(implementation = long.class, example = "100")) }) @GetMapping(value = "/define-user-count") @Res...
@Test public void testCountDefinitionByUser() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("projectId", "16"); MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/define-user-count") .header("sessionId", s...
public static KeyFormat sanitizeKeyFormat( final KeyFormat keyFormat, final List<SqlType> newKeyColumnSqlTypes, final boolean allowKeyFormatChangeToSupportNewKeySchema ) { return sanitizeKeyFormatWrapping( !allowKeyFormatChangeToSupportNewKeySchema ? keyFormat : sanitizeKeyFormat...
@Test public void shouldAddKeyWrappingWhenSanitizing() { // Given: final KeyFormat format = KeyFormat.nonWindowed( FormatInfo.of(JsonFormat.NAME), SerdeFeatures.of()); // When: final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyFormat(format, SINGLE_SQL_TYPE, true); // T...
@VisibleForTesting static Function<HiveColumnHandle, ColumnMetadata> columnMetadataGetter(Table table, TypeManager typeManager, ColumnConverter columnConverter, List<String> notNullColumns) { ImmutableList.Builder<String> columnNames = ImmutableList.builder(); table.getPartitionColumns().stream(...
@Test public void testColumnMetadataGetter() { TypeManager mockTypeManager = new TestingTypeManager(); Column column1 = new Column("c1", HIVE_INT, Optional.empty(), Optional.of("some-metadata")); HiveColumnHandle hiveColumnHandle1 = new HiveColumnHandle( column1.getName()...
@Override public int getForwardingSourceField(int input, int targetField) { if (input != 0) { throw new IndexOutOfBoundsException(); } for (Map.Entry<Integer, FieldSet> e : fieldMapping.entrySet()) { if (e.getValue().contains(targetField)) { return e....
@Test void testAllForwardedSingleInputSemPropsInvalidIndex1() { assertThatThrownBy( () -> { SingleInputSemanticProperties sp = new SingleInputSemanticProperties .AllFieldsForw...
@Override public void register(URL url) { if (url == null) { throw new IllegalArgumentException("register url == null"); } if (url.getPort() != 0) { if (logger.isInfoEnabled()) { logger.info("Register: " + url); } } register...
@Test void testRegisterIfURLNULL() { Assertions.assertThrows(IllegalArgumentException.class, () -> { abstractRegistry.register(null); Assertions.fail("register url == null"); }); }
@Description("Given a (longitude, latitude) point, returns the surrounding Bing tiles at the specified zoom level") @ScalarFunction("bing_tiles_around") @SqlType("array(" + BingTileType.NAME + ")") public static Block bingTilesAround( @SqlType(StandardTypes.DOUBLE) double latitude, @...
@Test public void testBingTilesAround() { assertFunction( "transform(bing_tiles_around(30.12, 60, 1), x -> bing_tile_quadkey(x))", new ArrayType(VARCHAR), ImmutableList.of("0", "2", "1", "3")); assertFunction( "transform(bing_tiles_...
@Override public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) { Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems); Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems); //remove comment and blank item map. ...
@Test public void testAddItemBeforeHasItem() { ItemChangeSets changeSets = resolver.resolve(1, "x=y\na=b\nb=c\nc=d", mockBaseItemHas3Key()); Assert.assertEquals("x", changeSets.getCreateItems().get(0).getKey()); Assert.assertEquals(1, changeSets.getCreateItems().size()); Assert.assertEquals(3, change...
public void putIfNotNull(String key, String value) { if (value != null) put(key, value); }
@Test public void putIfNotNull() { EnvVars env = new EnvVars(); env.putIfNotNull("foo", null); assertTrue(env.isEmpty()); env.putIfNotNull("foo", "bar"); assertFalse(env.isEmpty()); }
public MessageType convert(Schema avroSchema) { if (!avroSchema.getType().equals(Schema.Type.RECORD)) { throw new IllegalArgumentException("Avro schema must be a record."); } return new MessageType(avroSchema.getFullName(), convertFields(avroSchema.getFields(), "")); }
@Test public void testLocalTimestampMicrosType() throws Exception { Schema date = LogicalTypes.localTimestampMicros().addToSchema(Schema.create(LONG)); Schema expected = Schema.createRecord( "myrecord", null, null, false, Arrays.asList(new Schema.Field("timestamp", date, null, null))); testRoundT...
public static <T> Iterator<T> prepend(T prepend, @Nonnull Iterator<? extends T> iterator) { checkNotNull(iterator, "iterator cannot be null."); return new PrependIterator<>(prepend, iterator); }
@Test public void prependEmptyIterator() { var actual = IterableUtil.prepend(1, Collections.emptyIterator()); assertIteratorsEquals(List.of(1), actual); }
public synchronized boolean subscribe(Set<String> topics, Optional<ConsumerRebalanceListener> listener) { registerRebalanceListener(listener); setSubscriptionType(SubscriptionType.AUTO_TOPICS); return changeSubscription(topics); }
@Test public void cantSubscribePatternAndTopic() { state.subscribe(Pattern.compile(".*"), Optional.of(rebalanceListener)); assertThrows(IllegalStateException.class, () -> state.subscribe(singleton(topic), Optional.of(rebalanceListener))); }
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test(description = "it should not contain user tags in the top level OpenAPI object") public void shouldNotContainTopLevelUserTags() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS); final NoPetOperationsFilter filter = new NoPetOperationsFilter(); final Op...
@Override public void checkDone() throws IllegalStateException { // If the range is empty, it is done if (range.getFrom().compareTo(range.getTo()) == 0) { return; } // If nothing was attempted, throws an exception checkState( lastAttemptedPosition != null, "Key range is non-...
@Test public void testCheckDoneSucceedsWhenFromIsEqualToTheEndOfTheRange() { final Timestamp from = Timestamp.ofTimeMicroseconds(10L); final TimestampRange range = TimestampRange.of(from, from); final TimestampRangeTracker tracker = new TimestampRangeTracker(range); // Method is void, succeeds if exc...
public String exportResources( VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface namingInterface, Repository repository, IMetaStore metaStore ) throws KettleException { String resourceName = null; try { // Handle naming for both repository and XML bases resour...
@Test public void shouldUseExistingRepositoryDirectoryWhenExporting() throws KettleException { final JobMeta jobMetaSpy = spy( jobMeta ); JobMeta jobMeta = new JobMeta() { @Override public Object realClone( boolean doClear ) { return jobMetaSpy; } }; jobMeta.setRepositoryDire...
Record convert(Object data) { return convert(data, null); }
@Test public void testEvolveTypeDetectionStructNested() { org.apache.iceberg.Schema structColSchema = new org.apache.iceberg.Schema( NestedField.required(1, "ii", IntegerType.get()), NestedField.required(2, "ff", FloatType.get())); org.apache.iceberg.Schema tableSchema = ...
@ScalarOperator(EQUAL) @SqlType(StandardTypes.BOOLEAN) @SqlNullable public static Boolean equal(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right) { return left == right; }
@Test public void testEqual() { assertFunction("TINYINT'37' = TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' = TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'17' = TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'17' = TINYINT'17'", BOOLEAN, true); }
public double sub(int i, int j, double b) { return A[index(i, j)] -= b; }
@Test public void testSub() { System.out.println("sub"); double[][] A = { { 0.7220180, 0.07121225, 0.6881997f}, {-0.2648886, -0.89044952, 0.3700456f}, {-0.6391588, 0.44947578, 0.6240573f} }; double[][] B = { {0.6881997...