focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override @NotNull public List<PartitionStatistics> select(Collection<PartitionStatistics> statistics, Set<Long> excludeTables) { long now = System.currentTimeMillis(); return statistics.stream() .filter(p -> p.getNextCompactionTime() <= now) .filter(p -> !exclude...
@Test public void testEmpty() { List<PartitionStatistics> statisticsList = new ArrayList<>(); Assert.assertEquals(0, selector.select(statisticsList, new HashSet<Long>()).size()); }
@Override public void publish(ScannerReportWriter writer) { List<Map.Entry<String, String>> properties = new ArrayList<>(cache.getAll().entrySet()); properties.add(constructScmInfo()); properties.add(constructCiInfo()); // properties that are automatically included to report so that // they can be...
@Test public void publish_writes_properties_to_report() { cache.put("foo1", "bar1"); cache.put("foo2", "bar2"); underTest.publish(writer); List<ScannerReport.ContextProperty> expected = Arrays.asList( newContextProperty("foo1", "bar1"), newContextProperty("foo2", "bar2"), newContex...
@Override public boolean hasConflict(ConcurrentOperation thisOperation, ConcurrentOperation otherOperation) { // TODO : UUID's can clash even for insert/insert, handle that case. Set<String> partitionBucketIdSetForFirstInstant = thisOperation .getMutatedPartitionAndFileIds() .stream() ...
@Test public void testConcurrentWritesWithDifferentPartition() throws Exception { createCommit(metaClient.createNewInstantTime()); HoodieActiveTimeline timeline = metaClient.getActiveTimeline(); // consider commits before this are all successful Option<HoodieInstant> lastSuccessfulInstant = timeline.g...
@Override public DataflowPipelineJob run(Pipeline pipeline) { // Multi-language pipelines and pipelines that include upgrades should automatically be upgraded // to Runner v2. if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) { List<String> experiments = fi...
@Test public void testUpdateNonExistentPipeline() throws IOException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Could not find running job named badjobname"); DataflowPipelineOptions options = buildPipelineOptions(); options.setUpdate(true); options.setJobName("badJobN...
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback); return bean; }
@Test void beansWithMethodsAnnotatedWithRecurringAnnotationNoCronOrIntervalWillThrowException() { // GIVEN final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor(); // WHEN & THEN assertThatThrownBy(() -> recurringJobPostProcessor.postProcessAfterIn...
@Override public boolean databaseExists(SnowflakeIdentifier database) { Preconditions.checkArgument( database.type() == SnowflakeIdentifier.Type.DATABASE, "databaseExists requires a DATABASE identifier, got '%s'", database); final String finalQuery = "SHOW SCHEMAS IN DATABASE IDENTIFI...
@Test public void testDatabaseDoesntExist() throws SQLException { when(mockResultSet.next()) .thenThrow(new SQLException("Database does not exist", "2000", 2003, null)) .thenThrow( new SQLException( "Database does not exist, or operation cannot be performed", "2000", 20...
public static BigDecimal ensureFit(final BigDecimal value, final Schema schema) { return ensureFit(value, precision(schema), scale(schema)); }
@Test public void shouldFailFitIfTruncationNecessary() { // When: final Exception e = assertThrows( KsqlException.class, () -> ensureFit(new BigDecimal("1.23"), DECIMAL_SCHEMA) ); // Then: assertThat(e.getMessage(), containsString("Cannot fit decimal '1.23' into DECIMAL(2, 1) with...
public TimelineWriteResponse putEntities(TimelineEntities entities, UserGroupInformation callerUgi) throws IOException { LOG.debug("putEntities(entities={}, callerUgi={})", entities, callerUgi); TimelineWriteResponse response = null; try { boolean isStorageUp = checkRetryWithSleep(); if (...
@Test void testPutEntityWithStorageDown() throws IOException { TimelineWriter writer = mock(TimelineWriter.class); TimelineHealth timelineHealth = new TimelineHealth(TimelineHealth. TimelineHealthStatus.CONNECTION_FAILURE, ""); when(writer.getHealthStatus()).thenReturn(timelineHealth); Config...
@Operation(summary = "countQueueState", description = "COUNT_QUEUE_STATE_NOTES") @GetMapping(value = "/queue-count") @ResponseStatus(HttpStatus.OK) @ApiException(QUEUE_COUNT_ERROR) public Result<Map<String, Integer>> countQueueState(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_U...
@Test public void testCountQueueState() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/queue-count") .header("sessionId", sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) ...
public static ObjectInputDecoder createDecoder(Type type, TypeManager typeManager) { String base = type.getTypeSignature().getBase(); switch (base) { case UnknownType.NAME: return o -> o; case BIGINT: return o -> (Long) o; case INTE...
@Test public void testDecimalObjectDecoders() { ObjectInputDecoder decoder; // short decimal decoder = createDecoder(createDecimalType(11, 10), typeManager); assertTrue(decoder.decode(decimal("1.2345678910")) instanceof HiveDecimal); // long decimal decoder = cr...
public static int checkPositiveOrZero(int n, String name) { if (n < 0) { throw new IllegalArgumentException(name + ": " + n + " (expected: >= 0)"); } return n; }
@Test(expected = IllegalArgumentException.class) public void checkPositiveOrZeroMustFailIfArgumentIsNegative() { RangeUtil.checkPositiveOrZero(-1, "var"); }
@Override public void storeRowInCache( DatabaseLookupMeta meta, RowMetaInterface lookupMeta, Object[] lookupRow, Object[] add ) { RowMetaAndData rowMetaAndData = new RowMetaAndData( lookupMeta, lookupRow ); if ( !map.containsKey( rowMetaAndData ) ) { map.put( rowMetaAndDat...
@Test public void storeRowInCacheTest() throws Exception { DatabaseLookupData databaseLookupData = mock( DatabaseLookupData.class ); DatabaseLookupMeta databaseLookupMeta = mock( DatabaseLookupMeta.class ); DefaultCache defaultCache = new DefaultCache( databaseLookupData, 10 ); when( databaseLookupMet...
@Override public int read() throws IOException { checkAndUseNewPos(); pos += 1; readBytes.increment(); readOperations.increment(); return internalStream.read(); }
@Test public void testReadOneByte() throws IOException { String objectName = rule.randomObjectName(); rule.client() .putObject(new PutObjectRequest(rule.bucket(), objectName, "0123456789".getBytes())); try (EcsSeekableInputStream input = new EcsSeekableInputStream( rule.client...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testIfInJoinClause() { analyze("SELECT * FROM (VALUES (1)) a (x) JOIN (VALUES (2)) b ON IF(a.x = 1, true, false)"); }
@Override public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException { Collection<TableMetaData> tableMetaDataList = new LinkedList<>(); try (Connection connection = material.getDataSource().getConnection()) { Map<String, Collection<ColumnMetaData>>...
@Test void assertLoadWithTables() throws SQLException { DataSource dataSource = mockDataSource(); ResultSet resultSet = mockTableMetaDataResultSet(); when(dataSource.getConnection().prepareStatement( "SELECT TABLE_CATALOG, TABLE_NAME, COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION,...
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception { Http2HeadersSink sink = new Http2HeadersSink( streamId, headers, maxHeaderListSize, validateHeaders); // Check for dynamic table size updates, which must occur at the beginning: ...
@Test public void testLiteralWithoutIndexingWithEmptyName() throws Http2Exception { decode("000005" + hex("value")); verify(mockHeaders, times(1)).add(EMPTY_STRING, of("value")); }
@Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } }
@Test(expected = IllegalArgumentException.class) public void shouldValidateStartingSlash() { new RestRouteSource("/test").validate(); }
public static boolean isCoreRequest(HeaderMap headers) { return headers.contains(ORIGIN) || headers.contains(ACCESS_CONTROL_REQUEST_HEADERS) || headers.contains(ACCESS_CONTROL_REQUEST_METHOD); }
@Test public void testIsCoreRequest() { HeaderMap headers = new HeaderMap(); assertThat(CorsUtil.isCoreRequest(headers), is(false)); headers = new HeaderMap(); headers.add(ORIGIN, ""); assertThat(CorsUtil.isCoreRequest(headers), is(true)); headers = new HeaderMap(); ...
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test @Category(NeedsRunner.class) public void testCreateWithUnserializableElements() throws Exception { List<UnserializableRecord> elements = ImmutableList.of( new UnserializableRecord("foo"), new UnserializableRecord("bar"), new UnserializableRecord("baz")); Cre...
public static Optional<String> getDatabaseNameByDatabasePath(final String databasePath) { Pattern pattern = Pattern.compile(getShardingSphereDataNodePath() + "/([\\w\\-]+)?", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(databasePath); return matcher.find() ? Optional.of(matcher.g...
@Test void assertGetDatabaseNameByDatabasePathHappyPath() { assertThat(ShardingSphereDataNode.getDatabaseNameByDatabasePath("/statistics/databases/db_name"), is(Optional.of("db_name"))); }
public static String generateDatabaseId(String baseString) { checkArgument(baseString.length() != 0, "baseString cannot be empty!"); String databaseId = generateResourceId( baseString, ILLEGAL_DATABASE_CHARS, REPLACE_DATABASE_CHAR, MAX_DATABASE_ID_LENGTH,...
@Test public void testGenerateDatabaseIdShouldReplaceUpperCaseLettersWithLowerCase() { String testBaseString = "TDa"; String actual = generateDatabaseId(testBaseString); assertThat(actual).matches("tda_\\d{8}_\\d{6}_\\d{6}"); }
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteComparisonExpression() { // Given: final ComparisonExpression parsed = parseExpression("1 < 2"); when(processor.apply(parsed.getLeft(), context)).thenReturn(expr1); when(processor.apply(parsed.getRight(), context)).thenReturn(expr2); // When: final Expression re...
@Override public GcsResourceId resolve(String other, ResolveOptions resolveOptions) { checkState( isDirectory(), String.format("Expected the gcsPath is a directory, but had [%s].", gcsPath)); checkArgument( resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) || resol...
@Test public void testResolveInvalidInputs() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("The resolved file: [tmp/] should not end with '/'."); toResourceIdentifier("gs://my_bucket/").resolve("tmp/", StandardResolveOptions.RESOLVE_FILE); }
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected) { return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected)); }
@Test public void iterableContainsAtLeastInOrderWithFailure() { expectFailureWhenTestingThat(asList(1, null, 3)).containsAtLeast(null, 1, 3).inOrder(); assertFailureKeys( "required elements were all found, but order was wrong", "expected order for required elements", "but was"); as...
public List<InterfaceIpAddress> prefixes() { if (!object.has(PREFIXES)) { return null; } List<InterfaceIpAddress> ips = Lists.newArrayList(); ArrayNode prefixes = (ArrayNode) object.path(PREFIXES); prefixes.forEach(i -> ips.add(InterfaceIpAddress.valueOf(i.asText()))...
@Test public void testPrefixes() throws Exception { assertThat(config.prefixes(), is(prefixes)); }
@Override public List<Application> getAllHandlers(final String scheme) { final List<Application> applications = new ArrayList<>(); final NSArray urls = workspace.URLsForApplicationsToOpenURL(NSURL.URLWithString(String.format("%s:/", scheme))); NSEnumerator enumerator = urls.objectEnumerator(...
@Test public void testGetAllHandlers() { assumeTrue(Factory.Platform.osversion.matches("12\\..*")); final List<Application> list = new WorkspaceSchemeHandler(new LaunchServicesApplicationFinder()).getAllHandlers("http:/"); assertFalse(list.isEmpty()); for(Application application : li...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserAccessToken that = (UserAccessToken) o; return Objects.equals(token, that.token); }
@Test void equals_whenAnotherInstanceAndDifferentToken_shouldReturnFalse() { UserAccessToken userAccessToken1 = new UserAccessToken("token1"); UserAccessToken userAccessToken2 = new UserAccessToken("token2"); assertThat(userAccessToken1.equals(userAccessToken2)).isFalse(); }
static ApplicationHistoryServer launchAppHistoryServer(String[] args) { Thread .setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler()); StringUtils.startupShutdownMessage(ApplicationHistoryServer.class, args, LOG); ApplicationHistoryServer appHistoryServer = null; try { ...
@Test @Timeout(60000) void testLaunchWithArguments() throws Exception { ExitUtil.disableSystemExit(); ApplicationHistoryServer historyServer = null; try { // Not able to modify the config of this test case, // but others have been customized to avoid conflicts String[] args = new Strin...
public static LockManager defaultLockManager() { return LOCK_MANAGER_DEFAULT; }
@Test public void testLoadDefaultLockManager() { assertThat(LockManagers.defaultLockManager()) .isInstanceOf(LockManagers.InMemoryLockManager.class); }
@Override public void emit(String emitKey, List<Metadata> metadataList, ParseContext parseContext) throws IOException, TikaEmitterException { if (metadataList == null || metadataList.size() == 0) { throw new TikaEmitterException("metadata list must not be null or of size 0"); } t...
@Test public void testBasic() throws Exception { EmitterManager emitterManager = EmitterManager.load(getConfig("tika-config-gcs.xml")); Emitter emitter = emitterManager.getEmitter("gcs"); List<Metadata> metadataList = new ArrayList<>(); Metadata m = new Metadata(); m.set("k1"...
@Nullable public String ensureBuiltinRole(String roleName, String description, Set<String> expectedPermissions) { Role previousRole = null; try { previousRole = roleService.load(roleName); if (!previousRole.isReadOnly() || !expectedPermissions.equals(previousRole.getPermissio...
@Test public void ensureBuiltinRole() throws Exception { final Role newRole = mock(Role.class); when(newRole.getId()).thenReturn("new-id"); when(roleService.load("test-role")).thenThrow(NotFoundException.class); when(roleService.save(any(Role.class))).thenReturn(newRole); ...
@Override public <T> T convert(DataTable dataTable, Type type) { return convert(dataTable, type, false); }
@Test void convert_to_map_of_string_to_string__throws_exception__blank_space() { DataTable table = parse("", "| | -90.258056 |", "| 37.618889 | -122.375 |", "| 47.448889 | -122.309444 |", "| 40.639722 | -73.778889 |"); CucumberDataTable...
@Restricted(NoExternalUse.class) public static int permissionsToMode(Set<PosixFilePermission> permissions) { PosixFilePermission[] allPermissions = PosixFilePermission.values(); int result = 0; for (PosixFilePermission allPermission : allPermissions) { result <<= 1; r...
@Test public void testPermissionsToMode() { assertEquals(0777, Util.permissionsToMode(PosixFilePermissions.fromString("rwxrwxrwx"))); assertEquals(0757, Util.permissionsToMode(PosixFilePermissions.fromString("rwxr-xrwx"))); assertEquals(0750, Util.permissionsToMode(PosixFilePermissions.fromS...
@Override public void onThrowing(final TargetAdviceObject target, final TargetAdviceMethod method, final Object[] args, final Throwable throwable, final String pluginType) { MetricsCollectorRegistry.<CounterMetricsCollector>get(config, pluginType).inc(getStatementType()); }
@Test void assertWithStatement() { StatementExecuteErrorsCountAdvice advice = new StatementExecuteErrorsCountAdvice(); advice.onThrowing(new TargetAdviceObjectFixture(), mock(TargetAdviceMethod.class), new Object[]{}, mock(IOException.class), "FIXTURE"); assertThat(MetricsCollectorRegistry.g...
@Override public Optional<InetAddress> getLocalInetAddress(Predicate<InetAddress> predicate) { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .filter(a -> a.getHostAddress() != null) .fi...
@Test public void getLocalInetAddress_returns_empty_if_no_local_addresses_match() { Optional<InetAddress> address = underTest.getLocalInetAddress(a -> false); assertThat(address).isEmpty(); }
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { if(containerService.isContainer(folder)) { final S3BucketCreateService service = new S3BucketCreateService(session); service.create(folder, StringUtils.isBlank(status.getRegion())...
@Test public void testDirectoryDeleteWithVersioning() throws Exception { final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path paren...
public JsonGetterContext getContext(String queryPath) { JsonGetterContext context = internalCache.get(queryPath); if (context != null) { return context; } context = new JsonGetterContext(queryPath); JsonGetterContext previousContextValue = internalCache.putIfAbsent(qu...
@Test public void testGetReturnsTheSameObject() { JsonGetterContextCache cache = new JsonGetterContextCache(4, 2); JsonGetterContext contextA = cache.getContext("a"); JsonGetterContext contextB = cache.getContext("b"); JsonGetterContext contextC = cache.getContext("c"); JsonG...
@Override public Map<String, Object> encode(Object object) throws EncodeException { if (object == null) { return Collections.emptyMap(); } try { ObjectParamMetadata metadata = getMetadata(object.getClass()); Map<String, Object> propertyNameToValue = new HashMap<String, Object>(); f...
@Test void defaultEncoder_normalClassWithValues() { Map<String, Object> expected = new HashMap<>(); expected.put("foo", "fooz"); expected.put("bar", "barz"); expected.put("fooAppendBar", "foozbarz"); NormalObject normalObject = new NormalObject("fooz", "barz"); Map<String, Object> encodedMap ...
public static Instant fromMillisOrIso8601(String time, String fieldName) { try { return Instant.ofEpochMilli(Long.parseLong(time)); } catch (NumberFormatException nfe) { // TODO: copied from PluginConfigurationProcessor, find a way to share better try { DateTimeFormatter formatter = ...
@Test public void testFromMillisOrIso8601_failed() { try { Instants.fromMillisOrIso8601("bad-time", "testFieldName"); Assert.fail(); } catch (IllegalArgumentException iae) { Assert.assertEquals( "testFieldName must be a number of milliseconds since epoch or an ISO 8601 formatted da...
public static TriggerStateMachine stateMachineForTrigger(RunnerApi.Trigger trigger) { switch (trigger.getTriggerCase()) { case AFTER_ALL: return AfterAllStateMachine.of( stateMachinesForTriggers(trigger.getAfterAll().getSubtriggersList())); case AFTER_ANY: return AfterFirstSt...
@Test public void testAfterWatermarkEarlyLateTranslation() { RunnerApi.Trigger trigger = RunnerApi.Trigger.newBuilder() .setAfterEndOfWindow( RunnerApi.Trigger.AfterEndOfWindow.newBuilder() .setEarlyFirings(subtrigger1) .setLateFirings(su...
@Injection( name = "PARTITION_OVER_TABLES" ) public void metaSetPartitionOverTables( String value ) { setPartitioningEnabled( "Y".equalsIgnoreCase( value ) ); }
@Test public void metaSetPartitionOverTables() { TableOutputMeta tableOutputMeta = new TableOutputMeta(); tableOutputMeta.metaSetPartitionOverTables( "Y" ); assertTrue( tableOutputMeta.isPartitioningEnabled() ); tableOutputMeta.metaSetPartitionOverTables( "N" ); assertFalse( tableOutputMeta.isPart...
public Mono<Void> createConsumerAcl(KafkaCluster cluster, CreateConsumerAclDTO request) { return adminClientService.get(cluster) .flatMap(ac -> createAclsWithLogging(ac, createConsumerBindings(request))) .then(); }
@Test void createsConsumerDependantAclsWhenTopicsAndGroupsSpecifiedByPrefix() { ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class); when(adminClientMock.createAcls(createdCaptor.capture())) .thenReturn(Mono.empty()); var principal = UUID.randomUUID()....
public WithoutJsonPath(JsonPath jsonPath) { this.jsonPath = jsonPath; }
@Test public void shouldBeDescriptive() { assertThat(withoutJsonPath("$.name"), hasToString(equalTo("without json path \"$['name']\""))); }
public static <LeftT, RightT> ByBuilder<LeftT, RightT> of( PCollection<LeftT> left, PCollection<RightT> right) { return named(null).of(left, right); }
@Test public void testBuild_ImplicitName() { final Pipeline pipeline = TestUtils.createTestPipeline(); final PCollection<String> left = TestUtils.createMockDataset(pipeline, TypeDescriptors.strings()); final PCollection<String> right = TestUtils.createMockDataset(pipeline, TypeDescriptors....
public static MonitoringInfoMetricName named(String urn, Map<String, String> labels) { return new MonitoringInfoMetricName(urn, labels); }
@Test public void testNullUrnThrows() { HashMap<String, String> labels = new HashMap<String, String>(); thrown.expect(IllegalArgumentException.class); MonitoringInfoMetricName.named(null, labels); }
public static Impl join(By clause) { return new Impl(new JoinArguments(clause)); }
@Test @Category(NeedsRunner.class) public void testUnderspecifiedCoGroup() { PCollection<Row> pc1 = pipeline .apply( "Create1", Create.of(Row.withSchema(CG_SCHEMA_1).addValues("user1", 1, "us").build())) .setRowSchema(CG_SCHEMA_1); PCollection<...
@Override public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFetch(final Bytes key) { return wrapped().backwardFetch(key); }
@Test public void shouldDelegateToUnderlyingStoreWhenBackwardFetching() { store.backwardFetch(bytesKey); verify(inner).backwardFetch(bytesKey); }
@Override public List<String> detect(ClassLoader classLoader) { List<File> classpathContents = classGraph .disableNestedJarScanning() .addClassLoader(classLoader) .scan(1) .getClasspathFiles(); return classpathContents.stream().map(File::getAbsolutePath...
@Test public void shouldDetectJarFiles() throws Exception { File jarFile = createTestTmpJarFile("test"); ClassLoader classLoader = new URLClassLoader(new URL[] {jarFile.toURI().toURL()}); ClasspathScanningResourcesDetector detector = new ClasspathScanningResourcesDetector(new ClassGraph()); L...
public static ColumnIndex build( PrimitiveType type, BoundaryOrder boundaryOrder, List<Boolean> nullPages, List<Long> nullCounts, List<ByteBuffer> minValues, List<ByteBuffer> maxValues) { return build(type, boundaryOrder, nullPages, nullCounts, minValues, maxValues, null, null); ...
@Test public void testStaticBuildBinary() { ColumnIndex columnIndex = ColumnIndexBuilder.build( Types.required(BINARY).as(UTF8).named("test_binary_utf8"), BoundaryOrder.ASCENDING, asList(true, true, false, false, true, false, true, false), asList(1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l), ...
private String hash(String password, String salt) { return new SimpleHash(HASH_ALGORITHM, password, salt).toString(); }
@Test public void testHash() throws Exception { assertThat(SHA1HashPasswordAlgorithm.hash("foobar")).isEqualTo("baae906e6bbb37ca5033600fcb4824c98b0430fb"); }
static RLMQuotaManagerConfig fetchQuotaManagerConfig(RemoteLogManagerConfig rlmConfig) { return new RLMQuotaManagerConfig(rlmConfig.remoteLogManagerFetchMaxBytesPerSecond(), rlmConfig.remoteLogManagerFetchNumQuotaSamples(), rlmConfig.remoteLogManagerFetchQuotaWindowSizeSeconds()); }
@Test public void testFetchQuotaManagerConfig() { Properties defaultProps = new Properties(); defaultProps.put("zookeeper.connect", kafka.utils.TestUtils.MockZkConnect()); appendRLMConfig(defaultProps); KafkaConfig defaultRlmConfig = KafkaConfig.fromProps(defaultProps); RLMQ...
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof KryoSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } KryoSerial...
@Test void tryingToRestoreWithNonExistingClassShouldBeIncompatible() throws IOException { TypeSerializerSnapshot<Animal> restoredSnapshot = kryoSnapshotWithMissingClass(); TypeSerializer<Animal> currentSerializer = new KryoSerializer<>(Animal.class, new SerializerConfigImpl()); ...
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void replaces_incompatible_intellij_idea_plugin() { RuntimeOptions options = parser .parse("--plugin", "org.jetbrains.plugins.cucumber.java.run.CucumberJvm3SMFormatter") .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugins.setEv...
@Override public DeleteTopicsResult deleteTopics(final TopicCollection topics, final DeleteTopicsOptions options) { if (topics instanceof TopicIdCollection) return DeleteTopicsResult.ofTopicIds(handleDeleteTopicsUsingIds(((TopicIdCollection) topics).top...
@Test public void testDeleteTopicsDontRetryThrottlingExceptionWhenDisabled() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse( expectDeleteTopicsR...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { return payload.readInt8(); }
@Test void assertRead() { when(payload.readInt8()).thenReturn(1L); MySQLLongLongBinlogProtocolValue actual = new MySQLLongLongBinlogProtocolValue(); assertThat(actual.read(columnDef, payload), is(1L)); }
@Override public Set<ConfigOption<?>> requiredOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(HOSTNAME); options.add(KEYSPACE); options.add(TABLE_NAME); return options; }
@Test public void testValidation() { // validate illegal port try { Map<String, String> properties = getAllOptions(); properties.put("port", "123b"); createTableSource(properties); fail("exception expected"); } catch (Throwable t) { ...
public ProtocolBuilder name(String name) { this.name = name; return getThis(); }
@Test void name() { ProtocolBuilder builder = new ProtocolBuilder(); builder.name("name"); Assertions.assertEquals("name", builder.build().getName()); }
@Override public ByteBuf retainedSlice() { throw reject(); }
@Test void testRetainedSlice() { ByteBuf buf = Unpooled.buffer(10); int i = 0; while (buf.isWritable()) { buf.writeByte(i++); } ReplayingDecoderByteBuf buffer = new ReplayingDecoderByteBuf(buf); ByteBuf slice = buffer.retainedSlice(0, 4); assertEqu...
public static Checksum create() { return CHECKSUM_FACTORY.create(); }
@Test public void testUpdate() { final byte[] bytes = "Any String you want".getBytes(); final int len = bytes.length; Checksum crc1 = Crc32C.create(); Checksum crc2 = Crc32C.create(); Checksum crc3 = Crc32C.create(); crc1.update(bytes, 0, len); for (byte b :...
public Map<String, String> getAllProperties() { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); return builder.put(CONCURRENT_LIFESPANS_PER_TASK, String.valueOf(getConcurrentLifespansPerTask())) .put(ENABLE_SERIALIZED_PAGE_CHECKSUM, String.valueOf(isEnableSeria...
@Test public void testNativeExecutionVeloxConfig() { // Test defaults assertRecordedDefaults(ConfigAssertions.recordDefaults(NativeExecutionVeloxConfig.class) .setCodegenEnabled(false) .setSpillEnabled(true) .setAggregationSpillEnabled(true) ...
@Override public Result reconcile(Request request) { client.fetch(Tag.class, request.name()) .ifPresent(tag -> { if (ExtensionUtil.isDeleted(tag)) { if (removeFinalizers(tag.getMetadata(), Set.of(FINALIZER_NAME))) { client.update(tag); ...
@Test void reconcileDelete() { Tag tag = tag(); tag.getMetadata().setDeletionTimestamp(Instant.now()); tag.getMetadata().setFinalizers(Set.of(TagReconciler.FINALIZER_NAME)); when(client.fetch(eq(Tag.class), eq("fake-tag"))) .thenReturn(Optional.of(tag)); ArgumentC...
@Override public void transform(Message message, DataType fromType, DataType toType) { final Map<String, Object> headers = message.getHeaders(); CloudEvent cloudEvent = CloudEvents.v1_0; headers.putIfAbsent(CloudEvents.CAMEL_CLOUD_EVENT_ID, message.getExchange().getExchangeId()); he...
@Test void shouldMapToCloudEvent() throws Exception { Exchange exchange = new DefaultExchange(camelContext); exchange.getMessage().setHeader(BlobConstants.BLOB_NAME, "myBlob"); exchange.getMessage().setHeader(BlobConstants.E_TAG, "eTag"); exchange.getMessage().setBody(new ByteArrayI...
@Deprecated public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) { return Task.callable(name, () -> callable.call()); }
@Test public void testDelayTaskCompleted() throws InterruptedException { final Task<Integer> task = Task.callable(() -> 1234); final Task<Integer> taskWithDelay = task.withDelay(1, TimeUnit.SECONDS); getEngine().run(taskWithDelay); taskWithDelay.await(200, TimeUnit.MILLISECONDS); // Both tasks s...
@Override public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) { AbstractWALEvent result; byte[] bytes = new byte[data.remaining()]; data.get(bytes); String dataText = new String(bytes, StandardCharsets.UTF_8); if (decodeWithTX)...
@Test void assertDecodeWriteRowEventWithBoolean() { MppTableData tableData = new MppTableData(); tableData.setTableName("public.test"); tableData.setOpType("INSERT"); tableData.setColumnsName(new String[]{"data"}); tableData.setColumnsType(new String[]{"boolean"}); ta...
@Override public ScalarOperator visitBetweenPredicate(BetweenPredicateOperator predicate, Void context) { return shuttleIfUpdate(predicate); }
@Test void visitBetweenPredicate() { BetweenPredicateOperator operator = new BetweenPredicateOperator(true, new ColumnRefOperator(1, INT, "id", true), ConstantOperator.createInt(1), ConstantOperator.createInt(10)); { ScalarOperator newOperator = shuttle.vi...
@TargetApi(Build.VERSION_CODES.N) public static File getVolumeDirectory(StorageVolume volume) { try { Field f = StorageVolume.class.getDeclaredField("mPath"); f.setAccessible(true); return (File) f.get(volume); } catch (Exception e) { // This shouldn't fail, as mPath has been there in ...
@Test @Config(sdk = {P}) // min sdk is N public void testGetVolumeDirectory() throws Exception { StorageVolume mock = mock(StorageVolume.class); Field f = StorageVolume.class.getDeclaredField("mPath"); f.setAccessible(true); f.set(mock, new File("/storage/emulated/0")); File result = Utils.getV...
public synchronized static void clear(){ fallbackProviderCache.clear(); }
@Test public void clear() { MyNullResponseFallBackProvider myNullResponseFallBackProvider = new MyNullResponseFallBackProvider(); ZuulBlockFallbackManager.registerProvider(myNullResponseFallBackProvider); Assert.assertEquals(myNullResponseFallBackProvider.getRoute(), ROUTE); ZuulBloc...
@Udf public Integer len( @UdfParameter(description = "The input string") final String input) { if (input == null) { return null; } return input.length(); }
@Test public void shouldReturnNullForNullInput() { assertThat(udf.len((String) null), is(nullValue())); assertThat(udf.len((ByteBuffer) null), is(nullValue())); }
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); gauges.put("total.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit()); gauges.put("total.used", (Gauge<Long>) () -...
@Test public void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { when(nonHeap.getMax()).thenReturn(-1L); final Gauge gauge = (Gauge) gauges.getMetrics().get("non-heap.usage"); assertThat(gauge.getValue()) .isEqualTo(3.0); }
@Override public boolean isIn(String ipAddress) { //is cache expired //Uses Double Checked Locking using volatile if (cacheExpiryTimeStamp >= 0 && cacheExpiryTimeStamp < System.currentTimeMillis()) { synchronized(this) { //check if cache expired again if (cacheExpiryTimeStamp < Syste...
@Test public void testAddWithSleepForCacheTimeout() throws IOException, InterruptedException { String[] ips = {"10.119.103.112", "10.221.102.0/23", "10.113.221.221"}; TestFileBasedIPList.createFileWithEntries ("ips.txt", ips); CacheableIPList cipl = new CacheableIPList( new FileBasedIPList("ips...
@Override public void deleteTag(Long id) { // 校验存在 validateTagExists(id); // 校验标签下是否有用户 validateTagHasUser(id); // 删除 memberTagMapper.deleteById(id); }
@Test public void testDeleteTag_success() { // mock 数据 MemberTagDO dbTag = randomPojo(MemberTagDO.class); tagMapper.insert(dbTag);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbTag.getId(); // 调用 tagService.deleteTag(id); // 校验数据不存在了 assertNull(tagM...
@Override public List<Distribution.Method> getMethods(final Path container) { return Collections.singletonList(Distribution.CUSTOM); }
@Test public void testGetMethods() { assertEquals(Collections.singletonList(Distribution.CUSTOM), new CustomOriginCloudFrontDistributionConfiguration(new Host(new TestProtocol()), new DefaultX509TrustManager(), new DefaultX509KeyManager()).getMethods( new Path("/bbb",...
public static boolean supportCodegenForJavaSerialization(Class<?> cls) { // bean class can be static nested class, but can't be a non-static inner class // If a class is a static class, the enclosing class must not be null. // If enclosing class is null, it must not be a static class. try { return...
@Test public void testSupport() { assertTrue(CodegenSerializer.supportCodegenForJavaSerialization(Cyclic.class)); }
public static RpcStatus getStatus(String service) { return SERVICE_STATUS_MAP.computeIfAbsent(service, key -> new RpcStatus()); }
@Test public void getStatus() { RpcStatus rpcStatus1 = RpcStatus.getStatus(SERVICE); Assertions.assertNotNull(rpcStatus1); RpcStatus rpcStatus2 = RpcStatus.getStatus(SERVICE); Assertions.assertEquals(rpcStatus1, rpcStatus2); }
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldWorkAsExpectedWhenPassedAParseTreeInsteadOfString() { // Given: final ParserRuleContext tree = DefaultKsqlParser.getParseTree("DESCRIBE my_stream EXTENDED;"); // Then: Assert.assertEquals("DESCRIBE stream1 EXTENDED;", anon.anonymize(tree)); }
static void checkForDuplicates(ClassLoader classLoader, ILogger logger, String resourceName) { try { List<URL> resources = Collections.list(classLoader.getResources(resourceName)); if (resources.size() > 1) { String formattedResourceUrls = resources.stream().map(URL::toSt...
@Test public void should_log_warning_when_duplicate_found() throws Exception { URLClassLoader classLoader = classLoaderWithJars(dummyJarFile, duplicateJar(dummyJarFile)); DuplicatedResourcesScanner.checkForDuplicates(classLoader, logger, SOME_EXISTING_RESOURCE_FILE); ArgumentCaptor<String>...
@Override public void flush(ChannelHandlerContext ctx) throws Exception { if (readInProgress) { // If there is still a read in progress we are sure we will see a channelReadComplete(...) call. Thus // we only need to flush if we reach the explicitFlushAfterFlushes limit. ...
@Test public void testFlushViaReadComplete() { final AtomicInteger flushCount = new AtomicInteger(); EmbeddedChannel channel = newChannel(flushCount, false); // Flush should go through as there is no read loop in progress. channel.flush(); channel.runPendingTasks(); a...
public void createTopic(final String addr, final String defaultTopic, final TopicConfig topicConfig, final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException, MQClientException { Validators.checkTopicConfig(topicConfig); CreateTopicRequestHeader reques...
@Test public void testCreateTopic_Success() throws Exception { doAnswer((Answer<RemotingCommand>) mock -> { RemotingCommand request = mock.getArgument(1); RemotingCommand response = RemotingCommand.createResponseCommand(null); response.setCode(ResponseCode.SUCCESS); ...
public Tuple2<Long, Double> increase(String name, ImmutableMap<String, String> labels, Double value, long windowSize, long now) { ID id = new ID(name, labels); Queue<Tuple2<Long, Double>> window = windows.computeIfAbsent(id, unused -> new PriorityQueue<>()); synchronized (window) { w...
@Test public void testPT2M() { double[] actuals = parameters().stream().mapToDouble(e -> { Tuple2<Long, Double> increase = CounterWindow.INSTANCE.increase( "test", ImmutableMap.<String, String>builder().build(), e._2, Duration.parse("PT2M").getSeconds() * 1000, e....
@Override public void setResponseHeader(final String name, final String value) { final String headerName; if (RestConstants.HEADER_ID.equals(name)) { headerName = RestConstants.HEADER_ID; } else if (RestConstants.HEADER_RESTLI_ID.equals(name)) { headerName = RestConstants.HEADER_...
@Test(expectedExceptions = IllegalArgumentException.class) public void testSetIdHeader() throws RestLiSyntaxException { final ResourceContextImpl context = new ResourceContextImpl(); context.setResponseHeader(RestConstants.HEADER_ID, "foobar"); }
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); final Calendar calendar = readDateTime(data, 0); if (calendar == null) { onInvalidDataReceived(device, data); return; } onDateTimeReceived(device, calendar); }
@Test public void onInvalidDataReceived_dataTooShort() { final DataReceivedCallback callback = new DateTimeDataCallback() { @Override public void onDateTimeReceived(@NonNull final BluetoothDevice device, @NonNull final Calendar calendar) { assertEquals("Incorrect Date and Time reported as correct", 1, 2); ...
public static ResourceCalculatorProcessTree getResourceCalculatorProcessTree( String pid, Class<? extends ResourceCalculatorProcessTree> clazz, Configuration conf) { if (clazz != null) { try { Constructor <? extends ResourceCalculatorProcessTree> c = clazz.getConstructor(String.class); Res...
@Test void testCreateInstance() { ResourceCalculatorProcessTree tree; tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, new Configuration()); assertNotNull(tree); assertThat(tree, instanceOf(EmptyProcessTree.class)); }
public HikariDataSource getDataSource() { return ds; }
@Test @Ignore public void testGetPostgresDataSource() { DataSource ds = SingletonServiceFactory.getBean(PostgresDataSource.class).getDataSource(); assertNotNull(ds); try(Connection connection = ds.getConnection()){ assertNotNull(connection); } catch (SQLException e) ...
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetAnalyzerName() { String expected = "Libman Analyzer"; String actual = analyzer.getName(); assertEquals(expected, actual); }
@Override public void run() { // top-level command, do nothing }
@Test public void test_listSnapshots() { // Given // When run("list-snapshots"); // Then String actual = captureOut(); assertTrue("output should contain one line (the table header), but contains:\n" + actual, actual.trim().indexOf('\n') < 0 && !actual...
public static CompositeEvictionChecker newCompositeEvictionChecker(CompositionOperator compositionOperator, EvictionChecker... evictionCheckers) { Preconditions.isNotNull(compositionOperator, "composition"); Preconditions.isNotNull(e...
@Test(expected = IllegalArgumentException.class) public void compositionOperatorCannotBeNull() { CompositeEvictionChecker.newCompositeEvictionChecker( null, mock(EvictionChecker.class), mock(EvictionChecker.class)); }
public DataPoint getLastDataPoint() { return dataPoints.get(dataPoints.size() - 1); }
@Test public void testGetLastDataPoint() { cm = new ChartModel(FOO, BAR); long time = System.currentTimeMillis(); cm.addDataPoint(time) .data(FOO, VALUES1[0]) .data(BAR, VALUES2[0]); cm.addDataPoint(time + 1) .data(FOO, VALUES1[1]) ...
public static void main(String[] args) throws InterruptedException { var app = new App(); try { app.promiseUsage(); } finally { app.stop(); } }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(null)); }
@Override public double sd() { return Math.sqrt(k) * theta; }
@Test public void testSd() { System.out.println("sd"); GammaDistribution instance = new GammaDistribution(3, 2.1); instance.rand(); assertEquals(3.637307, instance.sd(), 1E-6); }
@Override public int hashCode() { return uniqueKey.hashCode(); }
@Test void testEqualsHashCode() { List<Pair<String>> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); Chooser<String, String> chooser = new Chooser<>("test", list); assertEquals("test".hashCode(), chooser.hashCode()); asser...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { // Metadata for the root folder is unsupported if(file.isRoot()) { // Retrieve the namespace ID for a users home folder and team root folder ...
@Test public void testFindFile() throws Exception { final Path root = new DefaultHomeFinderService(session).find(); final Path folder = new DropboxDirectoryFeature(session).mkdir(new Path(root, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), null); ...
@Override public int prepare(final Xid xid) throws XAException { try { return delegate.prepare(xid); } catch (final XAException ex) { throw mapXAException(ex); } }
@Test void assertPrepare() throws XAException { singleXAResource.prepare(xid); verify(xaResource).prepare(xid); }
@Override public FsCheckpointStateOutputStream createCheckpointStateOutputStream( CheckpointedStateScope scope) throws IOException { Path target = getTargetPath(scope); int bufferSize = Math.max(writeBufferSize, fileStateThreshold); // Whether the file system dynamically injects...
@Test void testEntropyMakesExclusiveStateAbsolutePaths() throws IOException { final FsStateBackendEntropyTest.TestEntropyAwareFs fs = new FsStateBackendEntropyTest.TestEntropyAwareFs(); final FsCheckpointStreamFactory factory = createFactory(fs, 0); final FsCheckpointStreamF...
public void tx(VoidFunc1<Session> func) throws SQLException { try { beginTransaction(); func.call(this); commit(); } catch (Throwable e) { quietRollback(); throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e); } }
@Test @Disabled public void txTest() throws SQLException { Session.create("test").tx(session -> session.update(Entity.create().set("age", 78), Entity.create("user").set("name", "unitTestUser"))); }
public static IpAddress valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new IpAddress(Version.INET, bytes); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfShortArrayIPv6() { IpAddress ipAddress; byte[] value; value = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); }
@Override @Async public void onApplicationEvent(MockInvocationEvent event) { log.debug("Received a MockInvocationEvent on {} - v{}", event.getServiceName(), event.getServiceVersion()); // Compute day string representation. Calendar calendar = Calendar.getInstance(); calendar.setTime(event...
@Test void testOnApplicationEvent() { Calendar today = Calendar.getInstance(); MockInvocationEvent event = new MockInvocationEvent(this, "TestService1", "1.0", "123456789", today.getTime(), 100); // Fire event a first time. feeder.onApplicationEvent(event); SimpleDateForma...
public static CsvWriter getWriter(String filePath, Charset charset) { return new CsvWriter(filePath, charset); }
@Test @Disabled public void writeWrapTest(){ List<List<Object>> resultList=new ArrayList<>(); List<Object> list =new ArrayList<>(); list.add("\"name\""); list.add("\"code\""); resultList.add(list); list =new ArrayList<>(); list.add("\"wang\""); list.add(1); resultList.add(list); String path = Fi...
@Override public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter, String methodName) throws Throwable { RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter); Object returnValue = proceedingJoinPoint.proceed(); return executeR...
@Test public void testReactorTypes() throws Throwable { RateLimiter rateLimiter = RateLimiter.ofDefaults("test"); when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test")); assertThat( rxJava2RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod")) ...
@Override public S3ClientBuilder createBuilder(S3Options s3Options) { return createBuilder(S3Client.builder(), s3Options); }
@Test public void testSetCredentialsProvider() { AwsCredentialsProvider credentialsProvider = mock(AwsCredentialsProvider.class); when(s3Options.getAwsCredentialsProvider()).thenReturn(credentialsProvider); DefaultS3ClientBuilderFactory.createBuilder(builder, s3Options); verify(builder).credentialsPr...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void shouldNotHaveNullInitializerOnAggregate() { assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(null)); }