focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static void initRequestHeader(HttpRequestBase requestBase, Header header) { Iterator<Map.Entry<String, String>> iterator = header.iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); requestBase.setHeader(entry.getKey(), entry.getValu...
@Test void testInitRequestHeader() { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); Header header = Header.newInstance(); header.addParam("k", "v"); HttpUtils.initRequestHeader(httpRequest, header); org.apache.http.H...
public EndpointResponse isValidProperty(final String property) { try { final Map<String, Object> properties = new HashMap<>(); properties.put(property, ""); denyListPropertyValidator.validateAll(properties); final KsqlConfigResolver resolver = new KsqlConfigResolver(); final Optional<C...
@Test public void shouldNotBadRequestWhenIsValidatorIsCalledWithNonQueryLevelProps() { final Map<String, Object> properties = new HashMap<>(); properties.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, ""); givenKsqlConfigWith(ImmutableMap.of( KsqlConfig.KSQL_SHARED_RUNTIME_ENABLED, true )); ...
public List<Pdu> getPdus() { return mPdus; }
@Test public void testCanParsePdusFromAltBeacon() { org.robolectric.shadows.ShadowLog.stream = System.err; byte[] bytes = hexStringToByteArray("02011a1aff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c50900000000000000000000000000000000000000000000000000000000000000"); BleAdvertisement ble...
@Transactional(readOnly = true) public User readUserIfValid(String username, String password) { Optional<User> user = userService.readUserByUsername(username); if (!isExistUser(user)) { log.warn("해당 유저가 존재하지 않습니다. username: {}", username); throw new UserErrorException(UserEr...
@DisplayName("로그인 시, 비밀번호가 일치하지 않으면 UserErrorException을 발생시킨다.") @Test void readUserIfNotMatchedPassword() { // given User user = UserFixture.GENERAL_USER.toUser(); given(userService.readUserByUsername(any())).willReturn(Optional.of(user)); given(passwordEncoder.matches("password...
public static String resolveRaw(String str) { int len = str.length(); if (len <= 4) { return null; } int endPos = len - 1; char last = str.charAt(endPos); // optimize to not create new objects if (last == ')') { char char1 = str.charAt(0)...
@Test void testURIScannerRawType1() { final String resolvedRaw1 = URIScanner.resolveRaw("RAW(++?w0rd)"); Assertions.assertEquals("++?w0rd", resolvedRaw1); }
public boolean start(Supplier<ManagedProcess> commandLauncher) { if (!lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.STARTING)) { // has already been started return false; } try { this.process = commandLauncher.get(); } catch (RuntimeException e) { LOG.error("Failed to launc...
@Test public void process_requests_are_listened_on_regular_basis() { ManagedProcessEventListener listener = mock(ManagedProcessEventListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addEventListener(listener) .setWatcherDelayMs(1L) .build(); try (TestMan...
public void unlink(Name name) { DirectoryEntry entry = remove(checkNotReserved(name, "unlink")); entry.file().unlinked(); }
@Test public void testUnlink_nonExistentNameFails() { try { dir.unlink(Name.simple("bar")); fail(); } catch (IllegalArgumentException expected) { } }
@Override public void start() { fetchInitialPipelineGlobalConfig(); schedulePeriodicGlobalConfigRequests(); }
@Test public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException { WorkItem firstConfig = new WorkItem() .setJobId("job") .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L)); WorkItem secondConfig = new Wo...
public static void checkPositiveInteger(long value, String argName) { checkArgument(value > 0, "'%s' must be a positive integer.", argName); }
@Test public void testCheckPositiveInteger() throws Exception { int positiveArg = 1; int zero = 0; int negativeArg = -1; // Should not throw. checkPositiveInteger(positiveArg, "positiveArg"); // Verify it throws. intercept(IllegalArgumentException.class, "'negativeArg' must be a...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldFetchWithNoBounds_fetchAll() { // When: table.get(PARTITION, Range.all(), Range.all()); // Then: verify(cacheBypassFetcherAll).fetchAll( eq(tableStore), eq(Instant.ofEpochMilli(0)), eq(Instant.ofEpochMilli(Long.MAX_VALUE)) ); }
public static SqlAggregation from(QueryDataType operandType, boolean distinct) { SqlAggregation aggregation = from(operandType); return distinct ? new DistinctSqlAggregation(aggregation) : aggregation; }
@Test @Parameters(method = "values_distinct") public void test_accumulateDistinct(QueryDataType operandType, List<Object> values, Object expected) { SqlAggregation aggregation = AvgSqlAggregations.from(operandType, true); aggregation.accumulate(null); values.forEach(aggregation::accumula...
public LocalPredictionId get(String fileName, String name) { return new LocalPredictionId(fileName, name); }
@Test void get() { LocalPredictionId retrieved = new PredictionIds().get(fileName, name); LocalPredictionId expected = new LocalPredictionId(fileName, name); assertThat(retrieved).isEqualTo(expected); }
public CruiseConfig deserializeConfig(String content) throws Exception { String md5 = md5Hex(content); Element element = parseInputStream(new ByteArrayInputStream(content.getBytes())); LOGGER.debug("[Config Save] Updating config cache with new XML"); CruiseConfig configForEdit = classPa...
@Test void shouldLoadConfigurationFileWithComplexNonEmptyString() throws Exception { String customerXML = loadWithMigration(Objects.requireNonNull(this.getClass().getResource("/data/p4_heavy_cruise_config.xml")).getFile()); assertThat(xmlLoader.deserializeConfig(customerXML)).isNotNull(); }
public boolean isSameAs(Component.Type otherType) { if (otherType.isViewsType()) { return otherType == this.viewsMaxDepth; } if (otherType.isReportType()) { return otherType == this.reportMaxDepth; } throw new UnsupportedOperationException(UNSUPPORTED_TYPE_UOE_MSG); }
@Test public void LEAVES_is_same_as_FILE_and_PROJECT_VIEW() { assertThat(CrawlerDepthLimit.LEAVES.isSameAs(Type.FILE)).isTrue(); assertThat(CrawlerDepthLimit.LEAVES.isSameAs(Type.PROJECT_VIEW)).isTrue(); for (Type type : from(asList(Type.values())).filter(not(in(ImmutableSet.of(Type.FILE, Type.PROJECT_VIE...
@Override public RegisterRMResponseProto convert2Proto(RegisterRMResponse registerRMResponse) { final short typeCode = registerRMResponse.getTypeCode(); final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType( MessageTypeProto.forNumber(typeCode)).b...
@Test public void convert2Proto() { RegisterRMResponse registerRMResponse = new RegisterRMResponse(); registerRMResponse.setResultCode(ResultCode.Failed); registerRMResponse.setMsg("msg"); registerRMResponse.setIdentified(true); registerRMResponse.setVersion("11"); r...
public static String toString(boolean bool, String trueString, String falseString) { return bool ? trueString : falseString; }
@Test public void toStringTest() { assertEquals("true", BooleanUtil.toStringTrueFalse(true)); assertEquals("false", BooleanUtil.toStringTrueFalse(false)); assertEquals("yes", BooleanUtil.toStringYesNo(true)); assertEquals("no", BooleanUtil.toStringYesNo(false)); assertEquals("on", BooleanUtil.toStringOnOff...
public static String writeValueAsString(Object value) { try { return OBJECT_MAPPER.writeValueAsString(value); } catch (JsonProcessingException e) { throw new IllegalArgumentException("The given Json object value: " + value + " cannot be transformed to a String...
@Test public void optionalMappingJDK8ModuleTest() { // To address the issue: Java 8 optional type `java.util.Optional` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jdk8" to enable handling assertThat(JacksonUtil.writeValueAsString(Optional.of("hello"))).isEqu...
@Nonnull @Override public Optional<? extends Algorithm> parse( @Nullable final String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } String algorithmStr; Optional<Mode> modeOptional = Optional.empty(); ...
@Test void blockSize() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaCipherMapper jcaCipherMapper = new JcaCipherMapper(); Optional<? extends Algorithm> cipherOptional = jcaCipherMapper.p...
public static void addSortedParams(UriBuilder uriBuilder, DataMap params, ProtocolVersion version) { if(version.compareTo(AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion()) >= 0) { addSortedParams(uriBuilder, params); } else { QueryParamsDataMap.addSortedParams(uriBuilder,...
@Test public void testProjectionMask() { DataMap queryParams = new DataMap(); DataMap fields = new DataMap(); fields.put("name", 1); DataMap friends = new DataMap(); friends.put("$start", 1); friends.put("$count", 2); fields.put("friends", friends); queryParams.put("fields", field...
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsNoneOf_primitiveDoubleArray_failure() { expectFailureWhenTestingThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsNoneOf(array(99.99, 2.2)); assertFailureKeys( "value of", "expected not to contain any o...
@Override public DataForm parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { DataForm.Type dataFormType = DataForm.Type.fromString(parser.getAttributeValue("", "type")); DataForm.Builder dataForm = DataForm...
@Test public void testRetrieveFieldWithEmptyLabel() throws XmlPullParserException, IOException, SmackParsingException { String form = "<x xmlns='jabber:x:data' type='form'>" + " <title>Advanced User Search</title>" + " <instructions>The foll...
public void popAsync(MessageQueue mq, long invisibleTime, int maxNums, String consumerGroup, long timeout, PopCallback popCallback, boolean poll, int initMode, boolean order, String expressionType, String expression) throws MQClientException, RemotingException, InterruptedException { ...
@Test public void testPopAsync() throws RemotingException, InterruptedException, MQClientException { PopCallback popCallback = mock(PopCallback.class); when(mQClientFactory.getMQClientAPIImpl()).thenReturn(mqClientAPIImpl); pullAPIWrapper.popAsync(createMessageQueue(), System...
@Override public NacosLoggingAdapter build() { return new Log4J2NacosLoggingAdapter(); }
@Test void build() { Log4j2NacosLoggingAdapterBuilder builder = new Log4j2NacosLoggingAdapterBuilder(); NacosLoggingAdapter adapter = builder.build(); assertNotNull(adapter); assertTrue(adapter instanceof Log4J2NacosLoggingAdapter); }
@Override public ResultSet getClientInfoProperties() throws SQLException { return createDatabaseMetaDataResultSet(getDatabaseMetaData().getClientInfoProperties()); }
@Test void assertGetClientInfoProperties() throws SQLException { when(databaseMetaData.getClientInfoProperties()).thenReturn(resultSet); assertThat(shardingSphereDatabaseMetaData.getClientInfoProperties(), instanceOf(DatabaseMetaDataResultSet.class)); }
public static PathOutputCommitter createCommitter(Path outputPath, TaskAttemptContext context) throws IOException { return getCommitterFactory(outputPath, context.getConfiguration()) .createOutputCommitter(outputPath, context); }
@Test public void testNamedCommitterFactory() throws Throwable { Configuration conf = new Configuration(); // set up for the schema factory conf.set(COMMITTER_FACTORY_CLASS, NAMED_COMMITTER_FACTORY); conf.set(NAMED_COMMITTER_CLASS, SimpleCommitter.class.getName()); SimpleCommitter sc = createCommi...
public static Builder builder() { return new Builder(); }
@Test void testMultipleWatermarks() { assertThatThrownBy( () -> TableSchema.builder() .field("f0", DataTypes.TIMESTAMP()) .field( ...
@Override public boolean shouldWait() { RingbufferContainer ringbuffer = getRingBufferContainerOrNull(); if (ringbuffer == null) { return true; } if (ringbuffer.isTooLargeSequence(sequence) || ringbuffer.isStaleSequence(sequence)) { //no need to wait, let the ...
@Test public void whenOneAfterTail() { ringbuffer.add("tail"); ReadOneOperation op = getReadOneOperation(ringbuffer.tailSequence() + 1); // since there is no item, we should wait boolean shouldWait = op.shouldWait(); assertTrue(shouldWait); }
public static FlinkJobServerDriver fromConfig(FlinkServerConfiguration configuration) { return create( configuration, createJobServerFactory(configuration), createArtifactServerFactory(configuration), () -> FlinkJobInvoker.create(configuration)); }
@Test public void testConfigurationFromConfig() { FlinkJobServerDriver.FlinkServerConfiguration config = new FlinkJobServerDriver.FlinkServerConfiguration(); FlinkJobServerDriver driver = FlinkJobServerDriver.fromConfig(config); assertThat(driver.configuration, is(config)); }
@Override public void populateDisplayData(DisplayData.Builder builder) { builder.delegate(delegate()); }
@Test public void populateDisplayDataDelegates() { doThrow(RuntimeException.class) .when(delegate) .populateDisplayData(any(DisplayData.Builder.class)); thrown.expect(RuntimeException.class); DisplayData.from(forwarding); }
@Override public Health health() { Map<String, Health> healths = rateLimiterRegistry.getAllRateLimiters().stream() .filter(this::isRegisterHealthIndicator) .collect(Collectors.toMap(RateLimiter::getName, this::mapRateLimiterHealth)); Status status = statusAggregator.getAggre...
@Test public void health() throws Exception { // given RateLimiterConfig config = mock(RateLimiterConfig.class); AtomicRateLimiter.AtomicRateLimiterMetrics metrics = mock( AtomicRateLimiter.AtomicRateLimiterMetrics.class); AtomicRateLimiter rateLimiter = mock(AtomicRateLi...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String targetObjectId = reader.readLine(); String methodName = reader.readLine(); List<Object> arguments = getArguments(reader); ReturnObject returnObject = invokeMethod(metho...
@Test public void testStringMethodWithNull() { String inputCommand = target + "\nmethod4\nn\ne\n"; try { command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yro1\n", sWriter.toString()); assertEquals(3, ((ExampleClass) gateway.getObject("o1")).getField1()); }...
@Override public void run() { logSubprocess(); }
@Test public void shouldLogDefaultMessageWhenNoMessageGiven() { logger = new SubprocessLogger(stubProcess()); String allLogs; try (LogFixture log = logFixtureFor(SubprocessLogger.class, Level.ALL)) { logger.run(); String result; synchronized (log) { ...
public static ConfigDefinitionKey parseConfigName(Element configE) { if (!configE.getNodeName().equals("config")) { throw new IllegalArgumentException("The root element must be 'config', but was '" + configE.getNodeName() + "'"); } if (!configE.hasAttribute("name")) { th...
@Test void testNameParsingInvalidNamespace() { assertThrows(IllegalArgumentException.class, () -> { Element configRoot = getDocument(new StringReader("<config name=\"_foo.function-test\" version=\"1\">" + "<int_val>1</int_val> +" + "</config>")); ...
public synchronized Map<String, ResourcePlugin> getNameToPlugins() { return configuredPlugins; }
@Test(timeout = 30000) public void testNodeStatusUpdaterWithResourcePluginsEnabled() throws Exception { final ResourcePluginManager rpm = stubResourcePluginmanager(); nm = new ResourcePluginMockNM(rpm); nm.init(conf); nm.start(); NodeResourceUpdaterPlugin nodeResourceUpdaterPlugin = ...
public void setProperty(String name, String value) { if (value == null) { return; } name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); if (prop == null) { addWarn("No such property [" + name + "] in " + objClass.getName() + "."); } else ...
@Test public void testFilterReply() { // test case reproducing bug #52 setter.setProperty("filterReply", "ACCEPT"); assertEquals(FilterReply.ACCEPT, house.getFilterReply()); }
@Override public TransportClient getClient(Map<String, ? extends Object> properties) { SSLContext sslContext; SSLParameters sslParameters; // Copy the properties map since we don't want to mutate the passed-in map by removing keys properties = new HashMap<String,Object>(properties); sslContext ...
@Test public void testSSLParams() throws Exception { HttpClientFactory factory = new HttpClientFactory.Builder().build(); Map<String,Object> params = new HashMap<>(); SSLParameters sslParameters = new SSLParameters(); sslParameters.setProtocols(new String[]{ "Unsupported" }); params.put(HttpCli...
boolean matchesNonValueField(final Optional<SourceName> source, final ColumnName column) { if (!source.isPresent()) { return sourceSchemas.values().stream() .anyMatch(schema -> SystemColumns.isPseudoColumn(column) || schema.isKeyColumn(column)); } final SourceName sourceName =...
@Test public void shouldMatchNonValueFieldNameIfAliasedKeyField() { assertThat(sourceSchemas.matchesNonValueField(Optional.of(ALIAS_2), K1), is(true)); }
@Override public DescriptiveUrl toUploadUrl(final Path file, final Sharee sharee, final Object options, final PasswordCallback callback) throws BackgroundException { final Host bookmark = session.getHost(); final StringBuilder request = new StringBuilder(String.format("https://%s%s/apps/files_sharin...
@Test public void testToUploadUrl() throws Exception { final Path home = new NextcloudHomeFeature(session.getHost()).find(); final Path folder = new DAVDirectoryFeature(session, new NextcloudAttributesFinderFeature(session)).mkdir(new Path(home, new AlphanumericRandomStringService().random(), EnumSe...
public static SimpleFunction<byte[], Row> getJsonBytesToRowFunction(Schema beamSchema) { return new JsonToRowFn<byte[]>(beamSchema) { @Override public Row apply(byte[] input) { String jsonString = byteArrayToJsonString(input); return RowJsonUtils.jsonToRow(objectMapper, jsonString); ...
@Test public void testGetJsonBytesToRowFunction() { for (TestCase<? extends RowEncodable> caze : testCases) { Row expected = caze.row; Row actual = JsonUtils.getJsonBytesToRowFunction(expected.getSchema()).apply(caze.jsonBytes); assertEquals(caze.userT.toString(), expected, actual); } }
void start(Iterable<ShardCheckpoint> checkpoints) { LOG.info( "Pool {} - starting for stream {} consumer {}. Checkpoints = {}", poolId, read.getStreamName(), consumerArn, checkpoints); for (ShardCheckpoint shardCheckpoint : checkpoints) { checkState( !stat...
@Test public void poolReSubscribesWhenNoRecordsCome() throws Exception { kinesis = new EFOStubbedKinesisAsyncClient(10); kinesis.stubSubscribeToShard("shard-000", eventsWithoutRecords(31, 3)); kinesis.stubSubscribeToShard("shard-001", eventsWithoutRecords(8, 3)); KinesisReaderCheckpoint initialCheckp...
public String getD() { return d; }
@Test public void testPublicJWKCreation() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { KeyPair keyPair = Keys.createSecp256k1KeyPair(); BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();...
@Override public void trash(final Local file) throws LocalAccessDeniedException { synchronized(NSWorkspace.class) { if(log.isDebugEnabled()) { log.debug(String.format("Move %s to Trash", file)); } // Asynchronous operation. 0 if the operation is performed ...
@Test public void testTrashRepeated() throws Exception { final WorkspaceTrashFeature f = new WorkspaceTrashFeature(); Local l = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); new DefaultLocalTouchFeature().touch(l); assertTrue(l.exists()); f.tr...
public void validate(ExternalIssueReport report, Path reportPath) { if (report.rules != null && report.issues != null) { Set<String> ruleIds = validateRules(report.rules, reportPath); validateIssuesCctFormat(report.issues, ruleIds, reportPath); } else if (report.rules == null && report.issues != nul...
@Test public void validate_whenMissingStartLineFieldForPrimaryLocation_shouldThrowException() throws IOException { ExternalIssueReport report = read(REPORTS_LOCATION); report.issues[0].primaryLocation.textRange.startLine = null; assertThatThrownBy(() -> validator.validate(report, reportPath)) .isIn...
public AccessPrivilege getAccessPrivilege(InetAddress addr) { return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName()); }
@Test public void testRegexGrouping() { NfsExports matcher = new NfsExports(CacheSize, ExpirationPeriod, "192.168.0.(12|34)"); Assert.assertEquals(AccessPrivilege.READ_ONLY, matcher.getAccessPrivilege(address1, hostname1)); // address1 will hit the cache Assert.assertEquals(AccessPrivi...
public static CronPattern of(String pattern) { return new CronPattern(pattern); }
@Test public void matchDayOfWeekTest() { // 星期四 CronPattern pattern = CronPattern.of("39 0 0 * * Thu"); assertMatch(pattern, "2017-02-09 00:00:39"); // 星期日的三种形式 pattern = CronPattern.of("39 0 0 * * Sun"); assertMatch(pattern, "2022-03-27 00:00:39"); pattern = CronPattern.of("39 0 0 * * 0"); assertMat...
public String getClientReturnId(String sessionId) { Optional<OpenIdSession> session = openIdRepository.findById(sessionId); if (session.isEmpty()) return null; OpenIdSession openIdSession = session.get(); var returnUrl = openIdSession.getRedirectUri() + "?state=" + openIdSession.getSt...
@Test void getClientReturnNotSuccess() { OpenIdSession openIdSession = new OpenIdSession(); when(httpServletRequest.getSession()).thenReturn(httpSession); when(httpSession.getId()).thenReturn(null); when(openIdRepository.findById(anyString())).thenReturn(Optional.of(openIdSession));...
public boolean isAfterFlink114() { return flinkInterpreter.getFlinkVersion().isAfterFlink114(); }
@Test void testBatchPyFlink() throws InterpreterException, IOException { if (!flinkInnerInterpreter.getFlinkVersion().isAfterFlink114()){ IPyFlinkInterpreterTest.testBatchPyFlink(interpreter, flinkScalaInterpreter); } }
@Override public void doRun() { final Instant mustBeOlderThan = Instant.now().minus(maximumSearchAge); searchDbService.getExpiredSearches(findReferencedSearchIds(), mustBeOlderThan).forEach(searchDbService::delete); }
@Test public void testForEmptySearches() { final ViewSummaryDTO view = mock(ViewSummaryDTO.class); when(viewService.streamAll()).thenReturn(Stream.of(view)); when(searchDbService.streamAll()).thenReturn(Stream.empty()); this.searchesCleanUpJob.doRun(); verify(searchDbServi...
@SuppressWarnings("checkstyle:MissingSwitchDefault") @Override protected void doCommit(TableMetadata base, TableMetadata metadata) { int version = currentVersion() + 1; CommitStatus commitStatus = CommitStatus.FAILURE; /* This method adds no fs scheme, and it persists in HTS that way. */ final Stri...
@Test void testDoCommitAppendAndDeleteSnapshots() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); List<Snapshot> extraTestSnapshots = IcebergTestUtil.getExtraSnapshots(); // add all snapshots to the base metadata TableMetadata base = BASE_TABLE_METADATA; for (Sn...
public abstract boolean compare(A actual, E expected);
@Test public void testTransforming_actual_compare_nullTransformedValues() { assertThat(HYPHEN_INDEXES.compare("mailing-list", null)).isFalse(); assertThat(HYPHEN_INDEXES.compare("forum", 7)).isFalse(); assertThat(HYPHEN_INDEXES.compare("forum", null)).isTrue(); }
public static String getNamenodeServiceAddr(final Configuration conf, String nsId, String nnId) { if (nsId == null) { nsId = getOnlyNameServiceIdOrNull(conf); } String serviceAddrKey = DFSUtilClient.concatSuffixes( DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY, nsId, nnId); S...
@Test public void getNameNodeServiceAddr() throws IOException { HdfsConfiguration conf = new HdfsConfiguration(); // One nameservice with two NNs final String NS1_NN1_HOST = "ns1-nn1.example.com:8020"; final String NS1_NN1_HOST_SVC = "ns1-nn2.example.com:9821"; final String NS1_NN2_HOST = "ns...
public SimpleRabbitListenerContainerFactory decorateSimpleRabbitListenerContainerFactory( SimpleRabbitListenerContainerFactory factory ) { return decorateRabbitListenerContainerFactory(factory); }
@Test void decorateSimpleRabbitListenerContainerFactory_prepends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); // the order of advices is important for the downstream interceptor to see the...
protected String getConnectionName( VFSFile vfsFile ) { String connectionName = null; if ( vfsFile != null ) { try { connectionName = getConnectionFileName( vfsFile ).getConnection(); } catch ( NullPointerException | FileException e ) { // DO NOTHING } } return connec...
@Test public void testGetConnectionName() throws Exception { assertNull( vfsFileProvider.getConnectionName( createTestFile( null ) ) ); assertNull( vfsFileProvider.getConnectionName( createTestFile( "" ) ) ); assertNull( vfsFileProvider.getConnectionName( createTestFile( " " ) ) ); assertNull( ...
public static String mainName(File file) { if (file.isDirectory()) { return file.getName(); } return mainName(file.getName()); }
@Test public void mainNameTest() { final String s = FileNameUtil.mainName("abc.tar.gz"); assertEquals("abc", s); }
@Nonnull public static <V> Set<V> findDuplicates(@Nonnull final Collection<V>... collections) { final Set<V> merged = new HashSet<>(); final Set<V> duplicates = new HashSet<>(); for (Collection<V> collection : collections) { for (V o : collection) { if (!merge...
@Test public void testSingleCollectionWithoutDuplicates() throws Exception { // Setup test fixture. final List<String> input = Arrays.asList("a", "b", "c"); // Execute system under test. @SuppressWarnings("unchecked") final Set<String> result = CollectionUtils.findDuplic...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIPv6DstTest() { Criterion criterion = Criteria.matchIPv6Dst(ipPrefix6); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
@Override public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final EnumSet<OpenMode> flags; if(status.isAppend()) { if(status.isExists()) { // No...
@Test public void testWriteRangeEndFirst() throws Exception { final SFTPWriteFeature feature = new SFTPWriteFeature(session); final Path test = new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final byte[] con...
public final String getName() { return getEnvironment().getTaskInfo().getTaskNameWithSubtasks(); }
@Test void testStateBackendLoadingAndClosing() throws Exception { Configuration taskManagerConfig = new Configuration(); taskManagerConfig.set(STATE_BACKEND, TestMemoryStateBackendFactory.class.getName()); StreamConfig cfg = new StreamConfig(new Configuration()); cfg.setStateKeySeri...
@Bean public ShenyuPlugin grpcPlugin() { return new GrpcPlugin(); }
@Test public void testGrpcPlugin() { applicationContextRunner.run(context -> { ShenyuPlugin plugin = context.getBean("grpcPlugin", ShenyuPlugin.class); assertNotNull(plugin); } ); }
@Override public void deleteById(HouseTablePrimaryKey houseTablePrimaryKey) { getHtsRetryTemplate(Arrays.asList(IllegalStateException.class)) .execute( context -> apiInstance .deleteTable( houseTablePrimaryKey.getDatabaseId(), houseTa...
@Test public void testRepoDelete() { mockHtsServer.enqueue( new MockResponse() .setResponseCode(204) .setBody("") .addHeader("Content-Type", "application/json")); Assertions.assertDoesNotThrow( () -> htsRepo.deleteById( HouseTabl...
public Type getType() { return token.getType(); }
@Test public void testEnclosing2() throws Exception { // If we don't override, the best we can get is List<Set<T>> // TypeRememberer<List<Set<String>>> rememberer = // new GenericMaker2<String>(){}.getGenericMaker().getRememberer(); // assertNotEquals( // new TypeToken<List<Set<String>>>() {...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { final String param = exchange.getAttribute(Constants.PARAM_TRANSFORM); ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);...
@Test public void testDoExecuteMetaDataError() { ServerWebExchange exchange = getServerWebExchange(); exchange.getAttributes().put(Constants.META_DATA, getMetaData()); RuleData data = mock(RuleData.class); StepVerifier.create(grpcPlugin.doExecute(exchange, chain, selector, data)).exp...
public static Object replace(Object root, DataIterator it, Object value) { return transform(root, it, Transforms.constantValue(value)); }
@Test public void testReplaceRoot() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); Object result = Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.dataSchemaNameEquals("Foo")) .replace(new DataMap()); assertTrue(re...
public static String join(Object[] a, char delimiter) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { sb.append(a[i]); if (i != a.length - 1) { sb.append(delimiter); } } return sb.toString(); }
@Test void testJoin() { String[] foo = {"a", "b"}; assertEquals("a,b", StringUtils.join(foo, ',')); assertEquals("a,b", StringUtils.join(Arrays.asList(foo), ",")); }
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = Securi...
@Test public void testIntKeysAndJSONToTextValues() { Integer key = 1234; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String value = "{\"a\": 1}"; putInCache("default", key, keyContentType, value, APPLICATION_JSON_TYPE); RestResponse response = get("defau...
@Override public AuthRuleGroup getServiceAuthRule(String service) { //TODO 暂不支持 return null; }
@Test public void getServiceAuthRule() { }
public void pruneColumns(Configuration conf, Path inputFile, Path outputFile, List<String> cols) throws IOException { RewriteOptions options = new RewriteOptions.Builder(conf, inputFile, outputFile) .prune(cols) .build(); ParquetRewriter rewriter = new ParquetRewriter(options); rewrite...
@Test public void testPruneNestedColumn() throws Exception { // Create Parquet file String inputFile = createParquetFile("input"); String outputFile = createTempFile("output"); // Remove nested column List<String> cols = Arrays.asList("Links.Backward"); columnPruner.pruneColumns(conf, new Pat...
public static ReportMetricsRequest fromJson(String json) { return JsonUtil.parse(json, ReportMetricsRequestParser::fromJson); }
@Test public void missingFields() { assertThatThrownBy(() -> ReportMetricsRequestParser.fromJson("{}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing string: report-type"); assertThatThrownBy( () -> ReportMetricsRequestParser.fromJson("{\"report-t...
@Override @Transactional(rollbackFor = Exception.class) public List<Long> createCodegenList(Long userId, CodegenCreateListReqVO reqVO) { List<Long> ids = new ArrayList<>(reqVO.getTableNames().size()); // 遍历添加。虽然效率会低一点,但是没必要做成完全批量,因为不会这么大量 reqVO.getTableNames().forEach(tableName -> ids.ad...
@Test public void testCreateCodegenList() { // 准备参数 Long userId = randomLongId(); CodegenCreateListReqVO reqVO = randomPojo(CodegenCreateListReqVO.class, o -> o.setDataSourceConfigId(1L).setTableNames(Collections.singletonList("t_yunai"))); // mock 方法(TableInfo) ...
public String getName() { final String path = uri.getPath(); final int slash = path.lastIndexOf(SEPARATOR); return path.substring(slash + 1); }
@Test void testGetName() { Path p = new Path("/my/fancy/path"); assertThat(p.getName()).isEqualTo("path"); p = new Path("/my/fancy/path/"); assertThat(p.getName()).isEqualTo("path"); p = new Path("hdfs:///my/path"); assertThat(p.getName()).isEqualTo("path"); ...
public QueueConfiguration getConfiguration() { return configuration; }
@Test public void testCreateEndpointWithMaxConfig() { context.getRegistry().bind("creds", new StorageSharedKeyCredential("fake", "fake")); final String uri = "azure-storage-queue://camelazure/testqueue" + "?credentials=#creds&operation=deleteQueue&timeToLive=PT100s&visibi...
public Optional<VersionedProfile> get(UUID uuid, String version) { Optional<VersionedProfile> profile = redisGet(uuid, version); if (profile.isEmpty()) { profile = profiles.get(uuid, version); profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile)); } return profile; }
@Test public void testGetProfileBrokenCache() { final UUID uuid = UUID.randomUUID(); final byte[] name = TestRandomUtil.nextBytes(81); final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, null, null, "somecommitment".getBytes()); when(commands.h...
public synchronized void synchronizeClusterSchemas( ClusterSchema clusterSchema ) { synchronizeClusterSchemas( clusterSchema, clusterSchema.getName() ); }
@Test public void synchronizeClusterSchemas() throws Exception { final String clusterSchemaName = "SharedClusterSchema"; TransMeta transformarion1 = createTransMeta(); ClusterSchema clusterSchema1 = createClusterSchema( clusterSchemaName, true ); transformarion1.setClusterSchemas( Collections.singleto...
@Override public void trackChannelEvent(String eventName) { }
@Test public void trackChannelEvent() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } });...
@Override public String getDestination() { return StringUtils.isBlank(destination) ? DEFAULT_ROOT.getPath() : FilenameUtils.separatorsToUnix(destination); }
@Test public void shouldNotOverrideDefaultArtifactDestinationWhenNotSpecified() { BuildArtifactConfig artifactConfig = new BuildArtifactConfig("src", null); assertThat(artifactConfig.getDestination(), is("")); TestArtifactConfig testArtifactConfig = new TestArtifactConfig("src", null); ...
public static CompilationUnit getFromFileName(String fileName) { try { final InputStream resource = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); return StaticJavaParser.parse(resource); } catch (ParseProblemException e) { throw new Kie...
@Test void getFromFileName() { CompilationUnit retrieved = JavaParserUtils.getFromFileName(TEMPLATE_FILE); assertThat(retrieved).isNotNull(); }
public Schema addToSchema(Schema schema) { validate(schema); schema.addProp(LOGICAL_TYPE_PROP, name); schema.setLogicalType(this); return schema; }
@Test void decimalWithNonByteArrayTypes() { final LogicalType decimal = LogicalTypes.decimal(5, 2); // test simple types Schema[] nonBytes = new Schema[] { Schema.createRecord("Record", null, null, false), Schema.createArray(Schema.create(Schema.Type.BYTES)), Schema.createMap(Schema.create(Schema....
public ProviderBuilder transporter(String transporter) { this.transporter = transporter; return getThis(); }
@Test void transporter() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.transporter("mocktransporter"); Assertions.assertEquals("mocktransporter", builder.build().getTransporter()); }
public static OP_TYPE getOpType(final List<Field<?>> fields, final Model model, final String targetFieldName) { return Stream.of(getOpTypeFromTargets(model.getTargets(), targetFieldName), getOpTypeFromMiningFields(model.getMiningSchema(), targetFieldName), getOp...
@Test void getOpTypeByMiningFields() { final Model model = new RegressionModel(); final DataDictionary dataDictionary = new DataDictionary(); final MiningSchema miningSchema = new MiningSchema(); IntStream.range(0, 3).forEach(i -> { final DataField dataField = getRandomDa...
@Override public void pickAddress() throws Exception { if (publicAddress != null || bindAddress != null) { return; } try { AddressDefinition publicAddressDef = getPublicAddressByPortSearch(); if (publicAddressDef != null) { publicAddress = ...
@Test public void testPublicAddress_withBlankAddress() { config.getNetworkConfig().setPublicAddress(" "); addressPicker = new DefaultAddressPicker(config, logger); assertThrows(IllegalArgumentException.class, () -> addressPicker.pickAddress()); }
public List<BingTile> findChildren() { return findChildren(zoomLevel + 1); }
@Test public void testFindChildren() { assertEquals( toSortedQuadkeys(BingTile.fromQuadKey("").findChildren()), ImmutableList.of("0", "1", "2", "3")); assertEquals( toSortedQuadkeys(BingTile.fromQuadKey("0123").findChildren()), Imm...
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema == null && value == null) { return null; } JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value); ...
@Test public void byteToJson() { JsonNode converted = parse(converter.fromConnectData(TOPIC, Schema.INT8_SCHEMA, (byte) 12)); validateEnvelope(converted); assertEquals(parse("{ \"type\": \"int8\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)); assertE...
public static <T> ListenableFuture<T> submit(final RequestBuilder<T> requestBuilder) { return transformFromTargetAndResult(submitInternal(requestBuilder)); }
@Test public void testBaseLoad() throws Exception { ColorDrawable expected = new ColorDrawable(Color.RED); ListenableFuture<Drawable> future = GlideFutures.submit(Glide.with(app).load(expected)); assertThat(((ColorDrawable) Futures.getDone(future)).getColor()).isEqualTo(expected.getColor()); }
@Draft public ZMsg msgBinaryPicture(String picture, Object... args) { if (!BINARY_FORMAT.matcher(picture).matches()) { throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(), ZError.EPROTO); } ZMsg msg = new ZMsg();...
@Test(expected = ZMQException.class) public void testInvalidBinaryPictureFormat() { String picture = "a"; pic.msgBinaryPicture(picture, 255); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { ThreadContext.unbindSubject(); final boolean secure = requestContext.getSecurityContext().isSecure(); final MultivaluedMap<String, String> headers = requestContext.getHeaders(); final Map<String...
@Test public void filterWithoutAuthorizationHeaderShouldDoNothing() throws Exception { final MultivaluedHashMap<String, String> headers = new MultivaluedHashMap<>(); when(requestContext.getHeaders()).thenReturn(headers); filter.filter(requestContext); final ArgumentCaptor<SecurityC...
@Override public Flux<BooleanResponse<ExpireCommand>> expire(Publisher<ExpireCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Mono<Boolean> m = write(keyB...
@Test public void testExpiration() { RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson); ReactiveStringRedisTemplate t = new ReactiveStringRedisTemplate(factory); t.opsForValue().set("123", "4343").block(); t.expire("123", Duration.ofMillis(1001)).block(); ...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public AppInfo get() { return getAppInfo(); }
@Test public void testAMXML() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("mapreduce") .accept(MediaType.APPLICATION_XML).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8, re...
@Override public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { try (InputStream input = provider.open(requireNonNull(path))) { final JsonNode node = mapper.readTree(createParser(input)); if (node == null) { th...
@Test void handlesExistingOverrideWithPeriod() throws Exception { System.setProperty("dw.my\\.logger.level", "debug"); final Example example = factory.build(configurationSourceProvider, validFile); assertThat(example.getLogger()) .containsEntry("level", "debug"); }
public String getCommandTopicName() { return commandTopic.getCommandTopicName(); }
@Test public void shouldGetCommandTopicName() { assertThat(commandStore.getCommandTopicName(), equalTo(COMMAND_TOPIC_NAME)); }
@SuppressWarnings("WeakerAccess") public Map<String, Object> getRestoreConsumerConfigs(final String clientId) { final Map<String, Object> baseConsumerProps = getCommonConsumerConfigs(); // Get restore consumer override configs final Map<String, Object> restoreConsumerProps = originalsWithPr...
@Test public void shouldBeSupportNonPrefixedRestoreConsumerConfigs() { props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> consumerConfigs = streamsConfig.getRestoreConsumerConfigs(groupId); ...
@Override public <S, C extends Config<S>> C createConfig(S subject, Class<C> configClass) { ConfigFactory<S, C> factory = getConfigFactory(configClass); Versioned<JsonNode> json = configs.computeIfAbsent(key(subject, configClass), k -> fac...
@Test public void testCreateConfig() { configStore.addConfigFactory(new MockConfigFactory(BasicConfig.class, "config1")); configStore.createConfig("config1", BasicConfig.class); assertThat(configStore.getConfigClasses("config1"), hasSize(1)); assertThat(configStore.getSubjects(Strin...
public void remove(ConnectorTaskId id) { final ScheduledFuture<?> task = committers.remove(id); if (task == null) return; try (LoggingContext loggingContext = LoggingContext.forTask(id)) { task.cancel(false); if (!task.isDone()) task.get(); ...
@Test public void testRemoveSuccess() { expectRemove(); committers.put(taskId, taskFuture); committer.remove(taskId); assertTrue(committers.isEmpty()); }
public static boolean isTrue(String b) { return b != null && StringUtils.TRUE.equalsIgnoreCase(b); }
@Test public void testIsTrue() { Assert.assertTrue(CommonUtils.isTrue("true")); Assert.assertTrue(CommonUtils.isTrue("True")); Assert.assertFalse(CommonUtils.isTrue("111")); Assert.assertFalse(CommonUtils.isTrue((String) null)); Assert.assertFalse(CommonUtils.isTrue("")); ...
@Nullable protected TagsExtractor getQuickTextTagsSearcher() { return mTagsExtractor; }
@Test public void testQuickTextEnabledPluginsPrefsChangedDoesNotCauseReloadIfTagsSearchIsDisabled() throws Exception { SharedPrefsHelper.setPrefsValue(R.string.settings_key_search_quick_text_tags, false); Assert.assertSame( TagsExtractorImpl.NO_OP, mAnySoftKeyboardUnderTest.getQuickTextTagsSearc...
public int getPrecision() { return precision; }
@Test public void default_precision_is_38() { DecimalColumnDef def = new DecimalColumnDef.Builder() .setColumnName("issues") .setScale(20) .setIsNullable(true) .build(); assertThat(def.getPrecision()).isEqualTo(38); }
public static RowCoder of(Schema schema) { return new RowCoder(schema); }
@Test public void testArrays() throws Exception { Schema schema = Schema.builder().addArrayField("f_array", FieldType.STRING).build(); Row row = Row.withSchema(schema).addArray("one", "two", "three", "four").build(); CoderProperties.coderDecodeEncodeEqual(RowCoder.of(schema), row); }
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull19() { // Arrange final int type = 19; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Table_map", actual); }
public static <T> T parseObject(String text, Class<T> clazz) { if (StringUtil.isBlank(text)) { return null; } return JSON_FACADE.parseObject(text, clazz); }
@Test public void assertParseObject() { Assert.assertNull(JSONUtil.parseObject(null, Foo.class)); Assert.assertNull(JSONUtil.parseObject(" ", Foo.class)); Assert.assertEquals(EXPECTED_FOO, JSONUtil.parseObject(EXPECTED_FOO_JSON, Foo.class)); }
public static boolean isValidOrigin(String sourceHost, ZeppelinConfiguration zConf) throws UnknownHostException, URISyntaxException { String sourceUriHost = ""; if (sourceHost != null && !sourceHost.isEmpty()) { sourceUriHost = new URI(sourceHost).getHost(); sourceUriHost = (sourceUriHost ==...
@Test void notAURIOrigin() throws URISyntaxException, UnknownHostException { assertFalse(CorsUtils.isValidOrigin("test123", ZeppelinConfiguration.load("zeppelin-site.xml"))); }
public WorkflowActionResponse deactivate(String workflowId, User caller) { Checks.notNull(caller, "caller cannot be null to deactivate workflow [%s]", workflowId); String timeline = workflowDao.deactivate(workflowId, caller); LOG.info(timeline); TimelineEvent event = TimelineActionEvent.builder(...
@Test public void testDeactivate() { when(workflowDao.deactivate("sample-minimal-wf", tester)).thenReturn("foo"); actionHandler.deactivate("sample-minimal-wf", tester); verify(workflowDao, times(1)).deactivate("sample-minimal-wf", tester); }