focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Applications(CuratorDb db) { this.db = db; // read and write all to make sure they are stored in the latest version of the serialized format for (ApplicationId id : ids()) { try (Mutex lock = db.lock(id)) { get(id).ifPresent(application -> put(application, lock...
@Test public void testApplications() { Applications applications = new NodeRepositoryTester().nodeRepository().applications(); ApplicationId app1 = ApplicationId.from("t1", "a1", "i1"); ApplicationId app2 = ApplicationId.from("t1", "a2", "i1"); ApplicationId app3 = ApplicationId.from...
@Override public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) { if (!shouldHandle(instances)) { return instances; } List<Object> result = getTargetInstancesByRules(targetName, instances); return super.handle(targetName, result, ...
@Test public void testGetTargetInstancesByConsumerTagRules() { RuleInitializationUtils.initConsumerTagRules(); List<Object> instances = new ArrayList<>(); Map<String, String> metadata1 = new HashMap<>(); metadata1.put("group", "red"); Map<String, String> metadata2 = new HashM...
@Override public Set<EntityExcerpt> listEntityExcerpts() { return eventDefinitionService.streamAll() .filter(ed -> ed.config().isContentPackExportable()) .map(this::createExcerpt) .collect(Collectors.toSet()); }
@Test public void listExcerptsExcludesNonContentPackExportableEventDefinitions() { EventDefinitionFacade testFacade = new EventDefinitionFacade( objectMapper, eventDefinitionHandler, new HashSet<>(), jobDefinitionService, mockEventDefinitionService, userService); EventDefinitionDto d...
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { if(file.isVolume()) { log.warn(String.format("Skip setting timestamp for %s", file)); return; } try { if(null != status.getModified()) { ...
@Test public void testSetTimestamp() throws Exception { final DriveFileIdProvider fileid = new DriveFileIdProvider(session); final Path home = DriveHomeFinderService.MYDRIVE_FOLDER; final Path test = new DriveTouchFeature(session, fileid).touch(new Path(home, new AlphanumericRandomStringServ...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selectorData, final RuleData rule) { SignRuleHandler ruleHandler = SignPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule)); if (ObjectUtils.isE...
@Test public void testSignPluginSignBody2() { this.ruleData.setHandle("{\"signRequestBody\": true}"); String requestBody = "{\"data\": \"4\"}"; this.exchange = MockServerWebExchange.from(MockServerHttpRequest .method(HttpMethod.POST, "/test?data2=3") .header(...
public static <T> T execute(Single<T> apiCall) { try { return apiCall.blockingGet(); } catch (HttpException e) { try { if (e.response() == null || e.response().errorBody() == null) { throw e; } String errorBody =...
@Test void executeNullErrorBodyThrowOriginalError() { // exception with a successful response creates an error without an error body HttpException httpException = new HttpException(Response.success(new CompletionResult())); Single<CompletionResult> single = Single.error(httpException); ...
@Override public void onLeaderInformationChange(String componentId, LeaderInformation leaderInformation) { synchronized (lock) { notifyLeaderInformationChangeInternal( componentId, leaderInformation, confirmedLeaderInformation.forCompon...
@Test void testAllLeaderInformationChangeEventWithPartialCorrection() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEven...
public static DatabaseType getStorageType(final DataSource dataSource) { try (Connection connection = dataSource.getConnection()) { return DatabaseTypeFactory.get(connection.getMetaData().getURL()); } catch (final SQLFeatureNotSupportedException sqlFeatureNotSupportedException) { ...
@Test void assertGetStorageType() throws SQLException { assertThat(DatabaseTypeEngine.getStorageType(mockDataSource(TypedSPILoader.getService(DatabaseType.class, "H2"))).getType(), is("H2")); }
public static File copyFilesFromDir(File src, File dest, boolean isOverride) throws IORuntimeException { return FileCopier.create(src, dest).setCopyContentIfDir(true).setOnlyCopyFile(true).setOverride(isOverride).copy(); }
@Test @Disabled public void copyFilesFromDirTest() { final File srcFile = FileUtil.file("D:\\驱动"); final File destFile = FileUtil.file("d:\\驱动备份"); FileUtil.copyFilesFromDir(srcFile, destFile, true); }
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testNightmareNoPb() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your Nightmare kill count is: <col=ff0000>1130</col>", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Team size: <col=ff0000>Solo</col> Fight...
@Override public String getMethodName() { return methodName; }
@Test void getMethodName() { Assertions.assertEquals("sayHello", method.getMethodName()); }
public static Schema fromTableSchema(TableSchema tableSchema) { return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build()); }
@Test public void testFromTableSchema_map_map() { Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_MAP_TYPE, INFER_MAPS_OPTIONS); assertEquals(MAP_MAP_TYPE, beamSchema); }
@Override public void checkAuthorization( final KsqlSecurityContext securityContext, final MetaStore metaStore, final Statement statement ) { if (statement instanceof Query) { validateQuery(securityContext, metaStore, (Query)statement); } else if (statement instanceof InsertInto) { ...
@Test public void shouldThrowWhenSingleSelectWithoutSubjectReadPermissionsDenied() { // Given: givenSubjectAccessDenied(AVRO_TOPIC + "-key", AclOperation.READ); final Statement statement = givenStatement(String.format( "SELECT * FROM %s;", AVRO_STREAM_TOPIC) ); // When: final Exceptio...
public static <T> AsSingleton<T> asSingleton() { return new AsSingleton<>(); }
@Test @Category(ValidatesRunner.class) public void testNonSingletonSideInput() throws Exception { PCollection<Integer> oneTwoThree = pipeline.apply(Create.of(1, 2, 3)); final PCollectionView<Integer> view = oneTwoThree.apply(View.asSingleton()); oneTwoThree.apply( "OutputSideInputs", P...
public static Base64URL getAccessTokenHash(JWSAlgorithm signingAlg, OAuth2AccessTokenEntity token) { byte[] tokenBytes = token.getJwt().serialize().getBytes(); return getHash(signingAlg, tokenBytes); }
@Test public void getAccessTokenHash256() { mockToken256.getJwt().serialize(); Base64URL expectedHash = new Base64URL("EP1gXNeESRH-n57baopfTQ"); Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.HS256, mockToken256); assertEquals(expectedHash, resultHash); }
static <T extends Comparable<? super T>> int compareListWithFillValue( List<T> left, List<T> right, T fillValue) { int longest = Math.max(left.size(), right.size()); for (int i = 0; i < longest; i++) { T leftElement = fillValue; T rightElement = fillValue; if (i < left.size()) { ...
@Test public void compareWithFillValue_nonEmptyListSameSizeGreaterValue_returnsPositive() { assertThat( ComparisonUtility.compareListWithFillValue( Lists.newArrayList(1, 3, 4), Lists.newArrayList(1, 2, 3), 100)) .isGreaterThan(0); }
@Udf(description = "Returns the hyperbolic cosine of an INT value") public Double cosh( @UdfParameter( value = "value", description = "The value in radians to get the hyperbolic cosine of." ) final Integer value ) { return cosh(value == null ? null : value...
@Test public void shouldHandleNegative() { assertThat(udf.cosh(-0.43), closeTo(1.0938833091357991, 0.000000000000001)); assertThat(udf.cosh(-Math.PI), closeTo(11.591953275521519, 0.000000000000001)); assertThat(udf.cosh(-Math.PI * 2), closeTo(267.7467614837482, 0.000000000000001)); assertThat(udf.cosh...
@Override public int getIteration() { return variables.getIteration(); }
@Test public void testGetIteration() { assertThat(unmodifiables.getIteration(), CoreMatchers.is(vars.getIteration())); }
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void testParseFailsOnUnparsableDate() throws Exception { assertThrows(NaturalDateParser.DateNotParsableException.class, () -> { naturalDateParser.parse("LOLWUT"); }); }
public QueryPath getPath() { return path; }
@Test public void testContent() { MapTableField field = new MapTableField("name", QueryDataType.INT, false, QueryPath.KEY_PATH); assertEquals("name", field.getName()); assertEquals(QueryDataType.INT, field.getType()); assertFalse(field.isHidden()); assertEquals(QueryPath.KEY...
@Override public Long getTimeMillis(K name) { return null; }
@Test public void testGetTimeMillisDefault() { assertEquals(1, HEADERS.getTimeMillis("name1", 1)); }
public boolean canProcessTask(final Task task, final long now) { final String topologyName = task.id().topologyName(); if (!hasNamedTopologies) { // TODO implement error handling/backoff for non-named topologies (needs KIP) return !pausedTopologies.contains(UNNAMED_TOPOLOGY); ...
@Test public void testNamedTopologiesCanBePausedIndependently() { final Set<String> pausedTopologies = new HashSet<>(); final TaskExecutionMetadata metadata = new TaskExecutionMetadata(NAMED_TOPOLOGIES, pausedTopologies, ProcessingMode.AT_LEAST_ONCE); final Task mockTask1 = createMockTask(T...
@Override @Nullable public Object convert(@Nullable String value) { if (isNullOrEmpty(value)) { return null; } LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone); final DateTimeFormatter form...
@Test public void testEmptyInput() throws Exception { final DateConverter converter = new DateConverter(config("yyyy-MM-dd'T'HH:mm:ss.SSSZ", null, null)); assertThat((DateTime) converter.convert("")).isNull(); }
@Override @MethodNotAvailable public void removeAll() { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveAllWithKeys() { adapter.removeAll(singleton(42)); }
static ParseResult parse(final int javaMajorVersion, final BufferedReader br) throws IOException { final ParseResult result = new ParseResult(); int lineNumber = 0; while (true) { final String line = br.readLine(); lineNumber++; if (line == null) { ...
@Test public void testParseOptionWithFixedVersion() throws IOException { JvmOptionsParser.ParseResult res = JvmOptionsParser.parse(11, asReader("8:-XX:+UseConcMarkSweepGC")); assertTrue("No option match for Java 11", res.getJvmOptions().isEmpty()); res = JvmOptionsParser.parse(8, asReader(...
public LoggerContext configure() { LoggerContext ctx = helper.getRootContext(); ctx.reset(); helper.enableJulChangePropagation(ctx); configureConsole(ctx); configureWithLogbackWritingToFile(ctx); helper.apply( LogLevelConfig.newBuilder(helper.getRootLoggerName()) .rootLevelFor(P...
@Test public void root_logger_writes_to_console_with_formatting_and_to_sonar_log_file_when_running_from_ITs() { emulateRunFromCommandLine(true); LoggerContext ctx = underTest.configure(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); verifyAppConsoleAppender(rootLogger.getAppender("APP_CONSOL...
@Override public final int readInt() throws EOFException { final int i = readInt(pos); pos += INT_SIZE_IN_BYTES; return i; }
@Test public void testReadInt() throws Exception { int readInt = in.readInt(); int theInt = Bits.readInt(INIT_DATA, 0, byteOrder == BIG_ENDIAN); assertEquals(theInt, readInt); }
public void compileToDestination(File src, File dst) throws IOException { for (Schema schema : queue) { OutputFile o = compile(schema); o.writeToDestination(src, dst); } if (protocol != null) { compileInterface(protocol).writeToDestination(src, dst); } }
@Test void pojoWithOptionalTurnedOffByDefault() throws IOException { SpecificCompiler compiler = createCompiler(); compiler.compileToDestination(this.src, OUTPUT_DIR); assertTrue(this.outputFile.exists()); try (BufferedReader reader = new BufferedReader(new FileReader(this.outputFile))) { String...
public static Function getFunctionOfRound(FunctionCallExpr node, Function fn, List<Type> argumentTypes) { return getFunctionOfRound(node.getParams(), fn, argumentTypes); }
@Test public void testGetFnOfTruncateForDecimalAndConstantExpression() { List<Expr> params = Lists.newArrayList(); params.add(new DecimalLiteral(new BigDecimal(new BigInteger("1845076"), 2))); params.add(new ArithmeticExpr(ArithmeticExpr.Operator.ADD, new IntLiteral(1), new IntLiteral(1))); ...
public synchronized void replayEraseTable(List<Long> tableIds) { List<RecycleTableInfo> removedTableInfos = removeTableFromRecycleBin(tableIds); for (RecycleTableInfo info : removedTableInfos) { info.table.deleteFromRecycleBin(info.dbId, true); } LOG.info("Finished replay era...
@Test public void testReplayEraseTable() { CatalogRecycleBin bin = new CatalogRecycleBin(); Table table = new Table(1L, "tbl", Table.TableType.HIVE, Lists.newArrayList()); bin.recycleTable(11, table, true); bin.recycleTable(12, table, true); List<Table> tables = bin.getTable...
public static String getPrefixedCacheName(String name, URI uri, ClassLoader classLoader) { String cacheNamePrefix = getPrefix(uri, classLoader); if (cacheNamePrefix != null) { return cacheNamePrefix + name; } else { return name; } }
@Test public void testGetPrefixedCacheName() { String prefix = getPrefixedCacheName(CACHE_NAME, uri, classLoader); assertEquals(expectedPrefixedCacheName, prefix); }
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldThrowOnUnknownSelectQualifier() { // Given: final SingleStatementContext stmt = givenQuery("SELECT unknown.COL0 FROM TEST1;"); // When: final Exception e = assertThrows( KsqlException.class, () -> builder.buildStatement(stmt) ); // Then: assertThat...
static void runDebuggingWordCount(WordCountOptions options) { Pipeline p = Pipeline.create(options); PCollection<KV<String, Long>> filteredWords = p.apply("ReadLines", TextIO.read().from(options.getInputFile())) .apply(new WordCount.CountWords()) .apply(ParDo.of(new FilterTextFn...
@Test public void testDebuggingWordCount() throws Exception { File inputFile = tmpFolder.newFile(); File outputFile = tmpFolder.newFile(); Files.asCharSink(inputFile, StandardCharsets.UTF_8) .write("stomach secret Flourish message Flourish here Flourish"); WordCountOptions options = TestPipeli...
@Override public void suspend(Throwable cause) { suspend(cause, null); }
@Test void testSuspendToFinished() throws Exception { try (MockStateWithExecutionGraphContext context = new MockStateWithExecutionGraphContext()) { final TestingStateWithExecutionGraph stateWithExecutionGraph = createStateWithExecutionGraph(context); ...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefin...
@Test public void testConvertDate() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("date").dataType("date").build(); Column column = SqlServerTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), co...
public <S extends Exception, T extends TException> ExceptionHandler convertIfInstance(Class<S> source, Class<T> target) throws T { T targetException = null; if (source.isInstance(e)) { try { targetException = JavaUtils.newInstance(target, new Class[]{String.class}, new Object[]{e...
@Test public void testConvertIfInstance() { IOException ix = new IOException("IOException test"); try { handleException(ix).convertIfInstance(NoSuchObjectException.class, MetaException.class); } catch (Exception e) { fail("Exception should not happen:" + e.getMessage()); } try { ...
@InvokeOnHeader(Web3jConstants.ETH_GET_UNCLE_COUNT_BY_BLOCK_HASH) void ethGetUncleCountByBlockHash(Message message) throws IOException { String blockHash = message.getHeader(Web3jConstants.BLOCK_HASH, configuration::getBlockHash, String.class); Request<?, EthGetUncleCountByBlockHash> request = web3j...
@Test public void ethGetUncleCountByBlockHashTest() throws Exception { EthGetUncleCountByBlockHash response = Mockito.mock(EthGetUncleCountByBlockHash.class); Mockito.when(mockWeb3j.ethGetUncleCountByBlockHash(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); ...
public static int checkNotNegative(int value, String paramName) { if (value < 0) { throw new IllegalArgumentException(paramName + " is " + value + " but must be >= 0"); } return value; }
@Test public void test_checkNotNegative_whenZero() { checkNotNegative(0, "foo"); }
public static String mask(String str) { if (str != null && str.length() > MASK_REMAIN) { char[] chars = str.toCharArray(); Arrays.fill(chars, 0, chars.length - MASK_REMAIN, '*'); return new String(chars); } return str; }
@Test public void testMask() { assertNull(mask(null)); assertEquals("", mask("")); assertEquals("123", mask("123")); assertEquals("123456", mask("123456")); assertEquals("****567890", mask("1234567890")); }
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testTransactionAbortedExceptionOnAbortWithoutError() throws InterruptedException { ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(123456L, (short) 0); TransactionManager txnManager = new TransactionManager(logContext, "testTransactionAbortedExceptionOnAbortWithoutEr...
@SqlNullable @Description("Returns the 2-dimensional cartesian minimum distance (based on spatial ref) between two geometries in projected units") @ScalarFunction("ST_Distance") @SqlType(DOUBLE) public static Double stDistance(@SqlType(GEOMETRY_TYPE_NAME) Slice left, @SqlType(GEOMETRY_TYPE_NAME) Slice r...
@Test public void testSTDistance() { assertFunction("ST_Distance(ST_Point(50, 100), ST_Point(150, 150))", DOUBLE, 111.80339887498948); assertFunction("ST_Distance(ST_Point(50, 100), ST_GeometryFromText('POINT (150 150)'))", DOUBLE, 111.80339887498948); assertFunction("ST_Distance(ST_Geom...
void handleStart(Exchange exchange, MetricRegistry registry, String metricsName) { String propertyName = getPropertyName(metricsName); Timer.Context context = getTimerContextFromExchange(exchange, propertyName); if (context == null) { Timer timer = registry.timer(metricsName); ...
@Test public void testHandleStart() { when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null); producer.handleStart(exchange, registry, METRICS_NAME); inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class); inOrder.verify(registry, ...
@Nonnull public static ToConverter getToConverter(QueryDataType type) { if (type.getTypeFamily() == QueryDataTypeFamily.OBJECT) { // User-defined types are subject to the same conversion rules as ordinary OBJECT. type = QueryDataType.OBJECT; } return Objects.requireNo...
@Test public void test_instantConversion() { OffsetDateTime time = OffsetDateTime.of(2020, 9, 8, 11, 4, 0, 0, UTC); Object converted = getToConverter(TIMESTAMP_WITH_TZ_INSTANT).convert(time); assertThat(converted).isEqualTo(Instant.ofEpochMilli(1599563040000L)); }
@Override public CompletableFuture<Void> cleanupAsync(JobID jobId) { mainThreadExecutor.assertRunningInMainThread(); CompletableFuture<Void> cleanupFuture = FutureUtils.completedVoidFuture(); for (CleanupWithLabel<T> cleanupWithLabel : prioritizedCleanup) { cleanupFuture = ...
@Test void testMediumPriorityCleanupBlocksAllLowerPrioritizedCleanups() { final SingleCallCleanup highPriorityCleanup = SingleCallCleanup.withCompletionOnCleanup(); final SingleCallCleanup lowerThanHighPriorityCleanup = SingleCallCleanup.withoutCompletionOnCleanup(); final Si...
@Override public void removePlugin(final PluginData pluginData) { super.getWasmExtern(REMOVE_PLUGIN_METHOD_NAME) .ifPresent(handlerPlugin -> callWASI(pluginData, handlerPlugin)); }
@Test public void removePluginTest() { pluginDataHandler.removePlugin(pluginData); testWasmPluginDataHandler.handlerPlugin(pluginData); testWasmPluginDataHandler.removePlugin(pluginData); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback); return bean; }
@Test void beansWithMethodsAnnotatedWithRecurringAnnotationCronAndIntervalWillThrowException() { // GIVEN final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor(); // WHEN & THEN assertThatThrownBy(() -> recurringJobPostProcessor.postProcessAfterIni...
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Counter counter = registry.counter(metricsName); Long increment = endpoint.getIncrement(); Long d...
@Test public void testProcessWithIncrementOnly() throws Exception { Object action = null; when(endpoint.getIncrement()).thenReturn(INCREMENT); when(endpoint.getDecrement()).thenReturn(null); when(in.getHeader(HEADER_COUNTER_INCREMENT, INCREMENT, Long.class)).thenReturn(INCREMENT); ...
Double applyRescaleFactor(double predictionDouble) { return predictionDouble * targetField.getRescaleFactor(); }
@Test void applyRescaleFactor() { TargetField targetField = new TargetField(Collections.emptyList(), null, "string", null, null, null, null, null); KiePMMLTarget kiePMMLTarget = getBuilder(targetField).build(); assertThat(kiePMMLTarget.applyR...
@Override public Long dbSize(RedisClusterNode node) { return execute(node, RedisCommands.DBSIZE); }
@Test public void testDbSize() { RedisClusterNode master = getFirstMaster(); Long size = connection.dbSize(master); assertThat(size).isZero(); }
public static boolean isDeprecated(PropertyKey key) { return DEPRECATED_CHECKER.hasAnnotation(key); }
@Test public void isDeprecated() throws Exception { assertFalse(PropertyKey.isDeprecated("alluxio.version")); }
public SerializationContext(Config config) { scopedMetaShareEnabled = config.isScopedMetaShareEnabled(); if (scopedMetaShareEnabled) { metaContext = new MetaContext(); } }
@Test public void testSerializationContext() { FuryBuilder builder = new FuryBuilder().withDeserializeNonexistentClass(false); builder.build(); // trigger finish SerializationContext context = new SerializationContext(new Config(builder)); assertFalse(context.containsKey("A")); context.add("A", 1)...
public boolean expireEntryIfNotSet(K key, Duration ttl, Duration maxIdleTime) { return get(expireEntryIfNotSetAsync(key, ttl, maxIdleTime)); }
@Test public void testExpireEntryIfNotSet() { RMapCache<String, String> testMap = redisson.getMapCache("map"); testMap.put("key", "value"); testMap.expireEntryIfNotSet("key", Duration.ofMillis(0), Duration.ofMillis(20000)); assertThat(testMap.remainTimeToLive("key")).isBetween(19800L...
public Tenant getTenant(TenantName tenantName) { return tenants.get(tenantName); }
@Test public void testStartUp() { assertEquals(tenantRepository.getTenant(tenant1).getName(), tenant1); assertEquals(tenantRepository.getTenant(tenant2).getName(), tenant2); }
public static TypeBuilder<Schema> builder() { return new TypeBuilder<>(new SchemaCompletion(), new NameContext()); }
@Test void duble() { Schema.Type type = Schema.Type.DOUBLE; Schema simple = SchemaBuilder.builder().doubleType(); Schema expected = primitive(type, simple); Schema built1 = SchemaBuilder.builder().doubleBuilder().prop("p", "v").endDouble(); assertEquals(expected, built1); }
public void unJar(File jarFile, File toDir) throws IOException { unJar(jarFile, toDir, MATCH_ANY); }
@Test public void testUnJarWithPattern() throws Exception { File unjarDir = getUnjarDir("unjar-pattern"); // Unjar only a regex RunJar.unJar(new File(TEST_ROOT_DIR, TEST_JAR_NAME), unjarDir, Pattern.compile(".*baz.*")); assertFalse("foobar not unpacked", ...
public Result waitForCondition(Config config, Supplier<Boolean>... conditionCheck) { return finishOrTimeout( config, conditionCheck, () -> jobIsDoneOrFinishing(config.project(), config.region(), config.jobId())); }
@Test public void testWaitForConditionTimeout() throws IOException { when(client.getJobStatus(any(), any(), any())).thenReturn(JobState.RUNNING); Result result = new PipelineOperator(client).waitForCondition(DEFAULT_CONFIG, () -> false); assertThat(result).isEqualTo(Result.TIMEOUT); }
public static Labels fromMap(Map<String, String> labels) { if (labels != null) { return new Labels(labels); } return EMPTY; }
@Test public void testParseNullLabelsInFromMap() { assertThat(Labels.fromMap(null), is(Labels.EMPTY)); }
public NetworkTopology getNetworkTopology() { return networktopology; }
@Test public void testNetworkTopologyInstantiation() throws Exception { // case 1, dfs.use.dfs.network.topology=true, use the default // DFSNetworkTopology impl. Configuration conf1 = new HdfsConfiguration(); FSNamesystem fsn = Mockito.mock(FSNamesystem.class); DatanodeManager dm1 = mockDatanodeMa...
@Override public boolean dropTable(TableIdentifier identifier, boolean purge) { if (!isValidIdentifier(identifier)) { return false; } String database = identifier.namespace().level(0); TableOperations ops = newTableOps(identifier); TableMetadata lastMetadata = null; if (purge) { ...
@Test public void testSetDefaultPartitionSpec() throws Exception { Schema schema = getTestSchema(); TableIdentifier tableIdent = TableIdentifier.of(DB_NAME, "tbl"); try { Table table = catalog.buildTable(tableIdent, schema).create(); assertThat(hmsTableParameters()) .as("Must not ha...
public URL[] getWatchResources() { return convertToURL(getProperty("watchResources")); }
@Test public void testGetWatchResources() throws Exception { PluginConfiguration pluginConfiguration = new PluginConfiguration(getClass().getClassLoader()); File tempFile = File.createTempFile("test", "test"); // find by URL pluginConfiguration.properties.setProperty("watchResources...
public Set<String> keySet() { return keys; }
@Test(expected = UnsupportedOperationException.class) public void testKeySet_isImmutable() { HazelcastProperties properties = new HazelcastProperties(config); properties.keySet().remove("foo"); }
public abstract Projection complement(int fieldsNumber);
@Test void testComplement() { assertThat(Projection.of(new int[] {4, 1, 2}).complement(5)) .isEqualTo(Projection.of(new int[] {0, 3})); assertThat( Projection.of(new int[][] {new int[] {4}, new int[] {1}, new int[] {2}}) .compl...
public static URI parse(String featureIdentifier) { requireNonNull(featureIdentifier, "featureIdentifier may not be null"); if (featureIdentifier.isEmpty()) { throw new IllegalArgumentException("featureIdentifier may not be empty"); } // Legacy from the Cucumber Eclipse plug...
@Test void can_parse_relative_file_form() { URI uri = FeaturePath.parse("file:path/to/file.feature"); assertAll( () -> assertThat(uri.getScheme(), is("file")), () -> assertThat(uri.getSchemeSpecificPart(), endsWith("path/to/file.feature"))); }
public static CsvWriter getWriter(String filePath, Charset charset) { return new CsvWriter(filePath, charset); }
@Test @Disabled public void writeDataTest(){ @Data @AllArgsConstructor class User { Integer userId; String username; String mobile; } List<String> header = ListUtil.of("用户id", "用户名", "手机号"); List<CsvRow> row = new ArrayList<>(); List<User> datas = new ArrayList<>(); datas.add(new User(1, "张...
@Override protected String buildHandle(final List<URIRegisterDTO> uriList, final SelectorDO selectorDO) { List<DivideUpstream> addList = buildDivideUpstreamList(uriList); List<DivideUpstream> canAddList = new CopyOnWriteArrayList<>(); boolean isEventDeleted = uriList.size() == 1 && EventType...
@Test public void testBuildHandle() { shenyuClientRegisterSpringCloudService = spy(shenyuClientRegisterSpringCloudService); final String returnStr = "{serviceId:'test1',gray:false,divideUpstreams:[{weight:50,warmup:10,protocol:" + "'http://',upstreamHost:'localhost',upstream...
@Udf(description = "Splits a string into an array of substrings based on a delimiter.") public List<String> split( @UdfParameter( description = "The string to be split. If NULL, then function returns NULL.") final String string, @UdfParameter( description = "The delimiter to spli...
@Test public void shouldSplitStringByGivenDelimiter() { assertThat(splitUdf.split("x-y", "-"), contains("x", "y")); assertThat(splitUdf.split("x-y", "x"), contains("", "-y")); assertThat(splitUdf.split("x-y", "y"), contains("x-", "")); assertThat(splitUdf.split("a.b.c.d", "."), contains("a", "b", "c",...
public void addValueProviders(final String segmentName, final RocksDB db, final Cache cache, final Statistics statistics) { if (storeToValueProviders.isEmpty()) { logger.debug("Adding metrics record...
@Test public void shouldThrowIfDbToAddWasAlreadyAddedForOtherSegment() { recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1); final Throwable exception = assertThrows( IllegalStateException.class, () -> recorder.addValueProviders(SEGMENT...
@Override public byte[] fromConnectHeader(String topic, String headerKey, Schema schema, Object value) { return fromConnectData(topic, schema, value); }
@Test public void testNonStringHeaderValueToBytes() { assertArrayEquals(Utils.utf8("true"), converter.fromConnectHeader(TOPIC, "hdr", Schema.BOOLEAN_SCHEMA, true)); }
public ValidationResult validateRoleConfiguration(final String pluginId, final Map<String, String> roleConfiguration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_ROLE_CONFIG, new DefaultPluginInteractionCallback<>() { @Override public String requestBody(String r...
@Test void shouldTalkToPlugin_To_ValidateRoleConfiguration() { String responseBody = "[{\"message\":\"memberOf must not be blank.\",\"key\":\"memberOf\"}]"; when(pluginManager.submitTo(eq(PLUGIN_ID), eq(AUTHORIZATION_EXTENSION), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResp...
@NonNull public String processShownotes() { String shownotes = rawShownotes; if (TextUtils.isEmpty(shownotes)) { Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message"); shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno...
@Test public void testProcessShownotesAddTimecodeHhmmNoChapters() { final String timeStr = "10:11"; final long time = 3600 * 1000 * 10 + 60 * 1000 * 11; String shownotes = "<p> Some test text with a timecode " + timeStr + " here.</p>"; ShownotesCleaner t = new ShownotesCleaner(conte...
public void log(final DriverEventCode code, final DirectBuffer buffer, final int offset, final int length) { if (DriverComponentLogger.ENABLED_EVENTS.contains(code)) { final int captureLength = captureLength(length); final int encodedLength = encodedLength(captureLength); ...
@Test void logIsNoOpIfEventIsNotEnabled() { buffer.setMemory(20, 100, (byte)5); logger.log(CMD_OUT_ERROR, buffer, 20, 100); assertEquals(0, logBuffer.getInt(lengthOffset(0), LITTLE_ENDIAN)); }
public static String removeStartingCharacters(String text, char ch) { int idx = 0; while (text.charAt(idx) == ch) { idx++; } if (idx > 0) { return text.substring(idx); } return text; }
@Test public void testRemoveInitialCharacters() { assertEquals("foo", StringHelper.removeStartingCharacters("foo", '/')); assertEquals("foo", StringHelper.removeStartingCharacters("/foo", '/')); assertEquals("foo", StringHelper.removeStartingCharacters("//foo", '/')); }
public static int read(final AtomicBuffer buffer, final EntryConsumer entryConsumer) { final int capacity = buffer.capacity(); int recordsRead = 0; int offset = 0; while (offset < capacity) { final long observationCount = buffer.getLongVolatile(offset + OBSERVAT...
@Test void shouldReadOneEntry() { final long initialBytesLost = 32; final int timestampMs = 7; final int sessionId = 3; final int streamId = 1; final String channel = "aeron:udp://stuff"; final String source = "127.0.0.1:8888"; lossReport.createEntry(init...
public void writeEncodedValue(EncodedValue encodedValue) throws IOException { switch (encodedValue.getValueType()) { case ValueType.BOOLEAN: writer.write(Boolean.toString(((BooleanEncodedValue) encodedValue).getValue())); break; case ValueType.BYTE: ...
@Test public void testWriteEncodedValue_byte() throws IOException { DexFormattedWriter writer = new DexFormattedWriter(output); writer.writeEncodedValue(new ImmutableByteEncodedValue((byte)0x12)); Assert.assertEquals("0x12", output.toString()); }
void recordLatency(String node, long requestLatencyMs) { fetchLatency.record(requestLatencyMs); if (!node.isEmpty()) { String nodeTimeName = "node-" + node + ".latency"; Sensor nodeRequestTime = this.metrics.getSensor(nodeTimeName); if (nodeRequestTime != null) ...
@Test public void testLatency() { metricsManager.recordLatency("", 123); time.sleep(metrics.config().timeWindowMs() + 1); metricsManager.recordLatency("", 456); assertEquals(289.5, metricValue(metricsRegistry.fetchLatencyAvg), EPSILON); assertEquals(456, metricValue(metricsR...
@Override protected void registerManagement() { if (!this.registration.isRegisterEnabled()) { return; } super.registerManagement(); }
@Test public void testRegisterManagement() { doReturn(false).when(registration).isRegisterEnabled(); assertThatCode(() -> { polarisAutoServiceRegistration.registerManagement(); }).doesNotThrowAnyException(); doReturn(true).when(registration).isRegisterEnabled(); assertThatCode(() -> { polarisAutoServi...
@Override public MavenArtifact searchSha1(String sha1) throws IOException { if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) { throw new IllegalArgumentException("Invalid SHA1 format"); } final URL url = new URL(rootURL, String.format("identify/sha1/%s", s...
@Test(expected = IllegalArgumentException.class) @Ignore public void testNullSha1() throws Exception { searcher.searchSha1(null); }
public static Script parse(byte[] program) throws ScriptException { return parse(program, TimeUtils.currentTime()); }
@Test public void testIp() { byte[] bytes = ByteUtils.parseHex("41043e96222332ea7848323c08116dddafbfa917b8e37f0bdf63841628267148588a09a43540942d58d49717ad3fabfe14978cf4f0a8b84d2435dad16e9aa4d7f935ac"); Script s = Script.parse(bytes); assertTrue(ScriptPattern.isP2PK(s)); }
public static FileEntriesLayer extraDirectoryLayerConfiguration( Path sourceDirectory, AbsoluteUnixPath targetDirectory, List<String> includes, List<String> excludes, Map<String, FilePermissions> extraDirectoryPermissions, ModificationTimeProvider modificationTimeProvider) thro...
@Test public void testExtraDirectoryLayerConfiguration_includesAndExcludesEverything() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); FileEntriesLayer layerConfiguration = JavaContainerBuilderHelper.extraDirectoryLayerC...
@Override public boolean isActive() { return task.isActive(); }
@Test public void shouldDelegateIsActive() { final ReadOnlyTask readOnlyTask = new ReadOnlyTask(task); readOnlyTask.isActive(); verify(task).isActive(); }
@Override public List<String> splitAndEvaluate() { try (ReflectContext context = new ReflectContext(JAVA_CLASSPATH)) { if (Strings.isNullOrEmpty(inlineExpression)) { return Collections.emptyList(); } return flatten(evaluate(context, GroovyUtils.split(handl...
@Test void assertEvaluateForExpressionIsNull() { InlineExpressionParser parser = TypedSPILoader.getService(InlineExpressionParser.class, "ESPRESSO", new Properties()); List<String> expected = parser.splitAndEvaluate(); assertThat(expected, is(Collections.<String>emptyList())); }
public Future<KafkaVersionChange> reconcile() { return getVersionFromController() .compose(i -> getPods()) .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testNoopWithAllVersions(VertxTestContext context) { String kafkaVersion = VERSIONS.defaultVersion().version(); String interBrokerProtocolVersion = VERSIONS.defaultVersion().protocolVersion(); String logMessageFormatVersion = VERSIONS.defaultVersion().messageVersion(); ...
@Override public Timestamp getTimestamp(final int columnIndex) throws SQLException { return (Timestamp) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Timestamp.class), Timestamp.class); }
@Test void assertGetTimestampAndCalendarWithColumnIndex() throws SQLException { Calendar calendar = Calendar.getInstance(); when(mergeResultSet.getCalendarValue(1, Timestamp.class, calendar)).thenReturn(new Timestamp(0L)); assertThat(shardingSphereResultSet.getTimestamp(1, calendar), is(new ...
SlackMessage createSlackMessage(EventNotificationContext ctx, SlackEventNotificationConfig config) throws PermanentEventNotificationException { String customMessage = null; String template = config.customMessage(); if (!isNullOrEmpty(template)) { // If the title is not included but ...
@Test public void createSlackMessage() throws EventNotificationException { String expectedText = "@channel *Alert _Event Definition Test Title_* triggered:\n> Event Definition Test Description \n"; SlackMessage actual = slackEventNotification.createSlackMessage(eventNotificationContext, slackEventNo...
static void maybeReportHybridDiscoveryIssue(PluginDiscoveryMode discoveryMode, PluginScanResult serviceLoadingScanResult, PluginScanResult mergedResult) { SortedSet<PluginDesc<?>> missingPlugins = new TreeSet<>(); mergedResult.forEach(missingPlugins::add); serviceLoadingScanResult.forEach(missin...
@Test public void testOnlyScanWithPlugins() { try (LogCaptureAppender logCaptureAppender = LogCaptureAppender.createAndRegister(Plugins.class)) { Plugins.maybeReportHybridDiscoveryIssue(PluginDiscoveryMode.ONLY_SCAN, empty, nonEmpty); assertTrue(logCaptureAppender.getEvents().stream(...
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testDoFnInvokersReused() throws Exception { // Ensures that we don't create a new Invoker class for every instance of the DoFn. IdentityParent fn1 = new IdentityParent(); IdentityParent fn2 = new IdentityParent(); assertSame( "Invoker classes should only be generated once for...
public String encode(long... numbers) { if (numbers.length == 0) { return ""; } for (final long number : numbers) { if (number < 0) { return ""; } if (number > MAX_NUMBER) { throw new IllegalArgumentException("numbe...
@Test public void test_for_vlues_greater_int_maxval() { final Hashids a = new Hashids("this is my salt"); Assert.assertEquals(a.encode(9876543210123L), "Y8r7W1kNN"); }
public void startTaskExecutors() { for (final TaskExecutor t: taskExecutors) { t.start(); } }
@Test public void shouldStartTaskExecutors() { taskManager.startTaskExecutors(); verify(taskExecutor).start(); }
@Override public SQLRecognizer getSelectForUpdateRecognizer(String sql, SQLStatement ast) { List<SQLHint> hints = ((SQLSelectStatement) ast).getSelect().getQueryBlock().getFrom().getHints(); if (CollectionUtils.isNotEmpty(hints)) { List<String> hintsTexts = hints .str...
@Test public void getSelectForUpdateTest() { //test with lock String sql = "SELECT name FROM t1 WITH (ROWLOCK, UPDLOCK) WHERE id = 'id1'"; SQLStatement sqlStatement = getSQLStatement(sql); Assertions.assertNotNull(new SqlServerOperateRecognizerHolder().getSelectForUpdateRecognizer(sq...
@Override public String name() { return name; }
@Test public void testSetSnapshotSummary() throws Exception { Configuration conf = new Configuration(); conf.set("iceberg.hive.table-property-max-size", "4000"); HiveTableOperations ops = new HiveTableOperations(conf, null, null, catalog.name(), DB_NAME, "tbl"); Snapshot snapshot = mock(Snapsh...
@Override public byte[] compress(byte[] payloadByteArr) { return payloadByteArr; }
@Test void compress() { byte[] input = new byte[] {1, 2, 3, 4, 5}; final byte[] compressed = Identity.IDENTITY.compress(input); Assertions.assertEquals(input, compressed); }
public CacheSimpleEntryListenerConfig setCacheEntryListenerFactory(String cacheEntryListenerFactory) { this.cacheEntryListenerFactory = cacheEntryListenerFactory; return this; }
@Test public void testEqualsAndHashCode() { assumeDifferentHashCodes(); CacheSimpleEntryListenerConfig redEntryListenerConfig = new CacheSimpleEntryListenerConfig(); redEntryListenerConfig.setCacheEntryListenerFactory("red"); CacheSimpleEntryListenerConfig blackEntryListenerConfig = ...
@Override public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) { ServerHttpResponse response = exchange.getResponse(); response.getHeaders().clear(); response.getHeaders().addAll(cachedResponse.headers()); }
@Test void headersFromCacheOverrideHeadersFromResponse() { SetResponseHeadersAfterCacheExchangeMutator toTest = new SetResponseHeadersAfterCacheExchangeMutator(); inputExchange.getResponse().getHeaders().set("X-Header-1", "Value-original"); CachedResponse cachedResponse = new CachedResponse.Builder(HttpStatus.OK...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeForeachRestartWithMutableOnStart() throws IOException { DefaultParamManager defaultParamManager = new DefaultParamManager(JsonHelper.objectMapperWithYaml()); defaultParamManager.init(); Map<String, ParamDefinition> allParams = defaultParamManager.getDefaultParams...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatInsertValuesStatement() { final String statementString = "INSERT INTO ADDRESS (NUMBER, STREET, CITY) VALUES (2, 'high', 'palo alto');"; final Statement statement = parseSingle(statementString); final String result = SqlFormatter.formatSql(statement); assertThat(result, ...
@Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { // will throw UnsupportedOperationException; delegate anyway for testability return underlying().compute(key, remappingFunction); }
@Test public void testDelegationOfUnsupportedFunctionCompute() { final BiFunction<Object, Object, Object> mockBiFunction = mock(BiFunction.class); new PCollectionsHashMapWrapperDelegationChecker<>() .defineMockConfigurationForUnsupportedFunction(mock -> mock.compute(eq(this), eq(mockBiFu...
public MergePolicyConfig getMergePolicyConfig() { return mergePolicyConfig; }
@Test public void cacheConfigXmlTest_DefaultMergePolicy() throws IOException { Config config = new XmlConfigBuilder(configUrl1).build(); CacheSimpleConfig cacheWithDefaultMergePolicyConfig = config.getCacheConfig("cacheWithDefaultMergePolicy"); assertNotNull(cacheWithDefaultMergePolicyConf...
public static String normalize(final String path) { return normalize(path, true); }
@Test public void testDoubleDot() { assertEquals("/", PathNormalizer.normalize("/..")); assertEquals("/p", PathNormalizer.normalize("/p/n/..")); assertEquals("/n", PathNormalizer.normalize("/p/../n")); assertEquals("/", PathNormalizer.normalize("..")); assertEquals("/", PathN...
@Override public Set<Map.Entry<String, Object>> entrySet() { return variables.entrySet(); }
@Test public void testEntrySet() { assertThat(unmodifiables.entrySet(), CoreMatchers.is(vars.entrySet())); }
@Override protected SemanticProperties getSemanticPropertiesForLocalPropertyFiltering() { // Local properties for GroupReduce may only be preserved on key fields. SingleInputSemanticProperties origProps = getOperator().getSemanticProperties(); SingleInputSemanticProperties filteredProps = ne...
@Test public void testGetSemanticProperties() { SingleInputSemanticProperties origProps = new SingleInputSemanticProperties(); origProps.addForwardedField(0, 1); origProps.addForwardedField(2, 2); origProps.addForwardedField(3, 4); origProps.addForwardedField(6, 0); ...