focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test(expected = NotfoundException.class) public void testMoveNotFound() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.f...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldSupportInsertIntoWithSchemaInferenceMatch() throws Exception { // Given: when(srClient.getLatestSchemaMetadata(Mockito.any())) .thenReturn(new SchemaMetadata(1, 1, "")); when(srClient.getSchemaById(1)) .thenReturn(new AvroSchema(AVRO_RAW_ONE_KEY_SCHEMA)); givenD...
@Override public void run() { updateElasticSearchHealthStatus(); updateFileSystemMetrics(); }
@Test public void when_elasticsearch_up_status_is_updated_to_green() { ClusterHealthResponse clusterHealthResponse = new ClusterHealthResponse(); clusterHealthResponse.setStatus(ClusterHealthStatus.GREEN); when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse); underTest.run(); ve...
@Override public Object toConnectRow(final Object ksqlData) { if (!(ksqlData instanceof Struct)) { return ksqlData; } final Schema schema = getSchema(); final Struct struct = new Struct(schema); Struct originalData = (Struct) ksqlData; Schema originalSchema = originalData.schema(); ...
@Test public void shouldThrowIfMissingField() { // Given: final Schema schema = SchemaBuilder.struct() .field("f1", SchemaBuilder.OPTIONAL_STRING_SCHEMA) .field("f3", SchemaBuilder.OPTIONAL_INT64_SCHEMA) .build(); final Struct struct = new Struct(ORIGINAL_SCHEMA) .put("f1",...
static SpecificData getModelForSchema(Schema schema) { final Class<?> clazz; if (schema != null && (schema.getType() == Schema.Type.RECORD || schema.getType() == Schema.Type.UNION)) { clazz = SpecificData.get().getClass(schema); } else { return null; } // If clazz == null, the underlyi...
@Test public void testModelForSpecificRecordWithoutLogicalTypes() { SpecificData model = AvroRecordConverter.getModelForSchema(Car.SCHEMA$); assertTrue(model.getConversions().isEmpty()); }
public static String getAttributesXml( Map<String, Map<String, String>> attributesMap ) { return getAttributesXml( attributesMap, XML_TAG ); }
@Test public void testGetAttributesXml_DefaultTag_NullParameter() { try ( MockedStatic<AttributesUtil> attributesUtilMockedStatic = mockStatic( AttributesUtil.class ) ) { attributesUtilMockedStatic.when( () -> AttributesUtil.getAttributesXml( anyMap() ) ).thenCallRealMethod(); attributesUtilMockedStat...
public ExponentialBackoff(long initialInterval, int multiplier, long maxInterval, double jitter) { this.initialInterval = Math.min(maxInterval, initialInterval); this.multiplier = multiplier; this.maxInterval = maxInterval; this.jitter = jitter; this.expMax = maxInterval > initia...
@Test public void testExponentialBackoff() { long scaleFactor = 100; int ratio = 2; long backoffMax = 2000; double jitter = 0.2; ExponentialBackoff exponentialBackoff = new ExponentialBackoff( scaleFactor, ratio, backoffMax, jitter ); for (int...
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("start position") BigDecimal start) { return invoke( list, start, null ); }
@Test void invokeStartPositive() { FunctionTestUtil.assertResult(sublistFunction.invoke(Arrays.asList(1, 2, 3), BigDecimal.valueOf(2)), Arrays.asList(2, 3)); FunctionTestUtil.assertResult(sublistFunction.invoke(Arrays.asList(1, "test", 3), BigDecimal.valueOf(2))...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test public void testNot() { final Predicate parsed = PredicateExpressionParser.parse("!com.linkedin.data.it.AlwaysTruePredicate"); Assert.assertEquals(parsed.getClass(), NotPredicate.class); Assert.assertEquals(((NotPredicate) parsed).getChildPredicate().getClass(), AlwaysTruePredicate.class); }
@Override public BulkFormat.Reader<T> createReader( final Configuration config, final FileSourceSplit split) throws IOException { final TrackingFsDataInputStream trackingStream = openStream(split.path(), config, split.offset()); final long splitEnd = split.offset() + spl...
@Test void testReadEmptyFile() throws IOException { final StreamFormatAdapter<Integer> format = new StreamFormatAdapter<>(new CheckpointedIntFormat()); final File emptyFile = new File(tmpDir.toFile(), "testFile-empty"); emptyFile.createNewFile(); Path emptyFilePath =...
@Override public List<String> validateText(String text, List<String> tags) { Assert.isTrue(ENABLED, "敏感词功能未开启,请将 ENABLED 设置为 true"); // 无标签时,默认所有 if (CollUtil.isEmpty(tags)) { return defaultSensitiveWordTrie.validate(text); } // 有标签的情况 Set<String> result ...
@Test public void testValidateText_hasTag() { testInitLocalCache(); // 准备参数 String text = "你是傻瓜,你是笨蛋"; // 调用 List<String> result = sensitiveWordService.validateText(text, singletonList("论坛")); // 断言 assertEquals(singletonList("傻瓜"), result); // 准备参数 ...
public static Read<String> readStrings() { return Read.newBuilder( (PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8)) .setCoder(StringUtf8Coder.of()) .build(); }
@Test public void testReadTopicDisplayData() { String topic = "projects/project/topics/topic"; PubsubIO.Read<String> read = PubsubIO.readStrings() .fromTopic(StaticValueProvider.of(topic)) .withTimestampAttribute("myTimestamp") .withIdAttribute("myId"); Display...
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 shouldFormatSelectStarCorrectly() { final String statementString = "CREATE STREAM S AS SELECT * FROM address;"; final Statement statement = parseSingle(statementString); assertThat(SqlFormatter.formatSql(statement), equalTo("CREATE STREAM S AS SELECT *\n" + "FROM ADDR...
@Override public QueryCacheScheduler getQueryCacheScheduler() { return queryCacheScheduler; }
@Test public void testGetQueryCacheScheduler() { QueryCacheScheduler scheduler = context.getQueryCacheScheduler(); assertNotNull(scheduler); final QuerySchedulerTask task = new QuerySchedulerTask(); scheduler.execute(task); final QuerySchedulerRepetitionTask repetitionTask ...
public static Integer subStringToInteger(String src, String start, String to) { return stringToInteger(subString(src, start, to)); }
@Test public void testSubStringToInteger() { Assert.assertNull(StringUtils.subStringToInteger("foobar", "1", "3")); Assert.assertEquals(new Integer(2), StringUtils.subStringToInteger("1234", "1", "3")); }
@Override public void preflight(final Path workdir, final String filename) throws BackgroundException { if(workdir.isRoot() || new DeepboxPathContainerService(session).isDeepbox(workdir) || new DeepboxPathContainerService(session).isBox(workdir)) { throw new AccessDeniedException(MessageFormat.f...
@Test public void testNoAddChildrenDocuments() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path folder = new Path("/ORG 1 - DeepBox Desktop App/ORG1:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final PathAttributes attrib...
@Override public RouteContext createRouteContext(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final SingleRule rule, final ConfigurationProperties props, final ConnectionContext connectionContext) { ...
@Test void assertCreateRouteContextWithMultiDataSource() throws SQLException { SingleRule rule = new SingleRule(new SingleRuleConfiguration(), DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), createMultiDataSourceMap(), Collections.emptyList()); ShardingSphereDatabase database = mockDatabaseWithMul...
public void installIntents(Optional<IntentData> toUninstall, Optional<IntentData> toInstall) { // If no any Intents to be uninstalled or installed, ignore it. if (!toUninstall.isPresent() && !toInstall.isPresent()) { return; } // Classify installable Intents to different ins...
@Test public void testInstallFailed() { installerRegistry.unregisterInstaller(TestInstallableIntent.class); installerRegistry.registerInstaller(TestInstallableIntent.class, new TestFailedIntentInstaller()); IntentData toUninstall = new IntentData(createTestIntent(), ...
public static String leftTruncate(@Nullable Object element, int maxLen) { if (element == null) { return ""; } String s = element.toString(); if (s.length() > maxLen) { return s.substring(0, maxLen) + "..."; } return s; }
@Test public void testLeftTruncate() { assertEquals("", StringUtils.leftTruncate(null, 3)); assertEquals("", StringUtils.leftTruncate("", 3)); assertEquals("abc...", StringUtils.leftTruncate("abcd", 3)); }
@Udf(description = "Returns the inverse (arc) cosine of an INT value") public Double acos( @UdfParameter( value = "value", description = "The value to get the inverse cosine of." ) final Integer value ) { return acos(value == null ? null : value.doubleValu...
@Test public void shouldHandleZero() { assertThat(udf.acos(0.0), closeTo(1.5707963267948966, 0.000000000000001)); assertThat(udf.acos(0), closeTo(1.5707963267948966, 0.000000000000001)); assertThat(udf.acos(0L), closeTo(1.5707963267948966, 0.000000000000001)); }
@Override protected ActivityState<TransportProtos.SessionInfoProto> updateState(UUID sessionId, ActivityState<TransportProtos.SessionInfoProto> state) { SessionMetaData session = sessions.get(sessionId); if (session == null) { return null; } state.setMetadata(session.get...
@Test void givenHasGwSessionIdButGwSessionIsNotNull_whenUpdatingActivityState_thenShouldReturnSameInstanceWithUpdatedSessionInfo() { // GIVEN var gwSessionId = UUID.fromString("19864038-9b48-11ee-b9d1-0242ac120002"); TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoP...
@Override public void submitPopConsumeRequest( final List<MessageExt> msgs, final PopProcessQueue processQueue, final MessageQueue messageQueue) { final int consumeBatchSize = this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize(); if (msgs.size() <= consumeBatchSize) { ...
@Test public void testSubmitPopConsumeRequest() throws IllegalAccessException { List<MessageExt> msgs = Collections.singletonList(createMessageExt()); PopProcessQueue processQueue = mock(PopProcessQueue.class); MessageQueue messageQueue = mock(MessageQueue.class); ThreadPoolExecutor ...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testIteration() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Integer> source = env.fromData(1, 2, 3).name("source"); IterativeStream<Integer> iteration = source.iterate(3000); iteration.name("iteration").setParallelis...
@Deprecated public String createToken(Authentication authentication) { return createToken(authentication.getName()); }
@Test void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException { createToken("SecretKey0123567890234567890123456789012345678901234567890123456789"); }
@Override public String getDisplayName() { return "map(" + keyType.getDisplayName() + ", " + valueType.getDisplayName() + ")"; }
@Test public void testMapDisplayName() { MapType mapType = new MapType( BIGINT, createVarcharType(42), MethodHandleUtil.methodHandle(TestMapType.class, "throwUnsupportedOperation"), MethodHandleUtil.methodHandle(TestMapType.class, "throwUns...
@SuppressWarnings("unchecked") private SpscChannelConsumer<E> newConsumer(Object... args) { return mapper.newFlyweight(SpscChannelConsumer.class, "ChannelConsumerTemplate.java", Template.fromFile(Channel.class, "ChannelConsumerTemplate.java"), args); }
@Test public void shouldNotReadUnCommittedMessages() { ChannelConsumer consumer = newConsumer(); assertTrue(producer.claim()); Example writer = producer.currentElement(); writer.setBar(10L); assertFalse(consumer.read()); }
public void enqueue(ByteBuffer payload) throws QueueException { final int messageSize = LENGTH_HEADER_SIZE + payload.remaining(); if (headSegment.hasSpace(currentHeadPtr, messageSize)) { LOG.debug("Head segment has sufficient space for message length {}", LENGTH_HEADER_SIZE + payload.remaini...
@Test public void basicNoBlockEnqueue() throws QueueException, IOException { final MappedByteBuffer pageBuffer = Utils.createPageFile(); final Segment head = new Segment(pageBuffer, new SegmentPointer(0, 0), new SegmentPointer(0, 1024)); final VirtualPointer currentHead = VirtualPointer.bui...
Set<String> getRetry() { return retry; }
@Test public void determineRetryWhenSetToRetryable() { Athena2QueryHelper helper = athena2QueryHelperWithRetry("retryable"); assertEquals(new HashSet<>(Collections.singletonList("retryable")), helper.getRetry()); }
@Override public boolean shutdownServiceUninterruptible(long timeoutMs) { final Deadline deadline = Deadline.fromNow(Duration.ofMillis(timeoutMs)); boolean shutdownComplete = false; boolean receivedInterrupt = false; do { try { // wait for a reasonable ...
@Test void testShutdownServiceUninterruptible() { final OneShotLatch blockUntilTriggered = new OneShotLatch(); final AtomicBoolean timerFinished = new AtomicBoolean(false); final SystemProcessingTimeService timeService = createBlockingSystemProcessingTimeService(blockUntilTr...
@Override public List<String> listPartitionNames(String databaseName, String tableName, TableVersionRange version) { updatePartitionInfo(databaseName, tableName); return new ArrayList<>(this.partitionInfos.keySet()); }
@Test public void testListPartitionNames(@Mocked FileStoreTable mockPaimonTable, @Mocked PartitionsTable mockPartitionTable, @Mocked RecordReader<InternalRow> mockRecordReader) throws Catalog.TableNotExistException, IOExceptio...
public URI rootUrl() { return this.build("/"); }
@Test void root() { assertThat(uriProvider.rootUrl().toString(), containsString("mysuperhost.com/subpath/")); }
public boolean removeByLine(int line) { boolean updated = problems.remove(line) != null; if (updated) Unchecked.checkedForEach(listeners, ProblemInvalidationListener::onProblemInvalidation, (listener, t) -> logger.error("Exception thrown when removing problem from tracking", t)); return updated; }
@Test void removeByLine() { ProblemTracking tracking = new ProblemTracking(); tracking.add(new Problem(0, 0, ERROR, LINT, "message")); tracking.add(new Problem(1, 0, ERROR, LINT, "message")); assertEquals(2, tracking.getProblems().size()); assertTrue(tracking.removeByLine(1)); assertEquals(1, tracking.get...
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_navigation_nonav() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("nonav", config); assertThat(config.navigation).isEqualTo(NAVIGATION_NONAV); }
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 shouldThrowIfCacheToAddIsNotSameAsAllExistingCaches() { recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1); recorder.addValueProviders(SEGMENT_STORE_NAME_2, dbToAdd2, cacheToAdd1, statisticsToAdd2); final Throwable exception = assertT...
@Override public DynamicTableSink createDynamicTableSink(Context context) { Configuration conf = FlinkOptions.fromMap(context.getCatalogTable().getOptions()); checkArgument(!StringUtils.isNullOrEmpty(conf.getString(FlinkOptions.PATH)), "Option [path] should not be empty."); setupTableOptions(conf....
@Test void testSetupWriteOptionsForSink() { final HoodieTableSink tableSink1 = (HoodieTableSink) new HoodieTableFactory().createDynamicTableSink(MockContext.getInstance(this.conf)); final Configuration conf1 = tableSink1.getConf(); assertThat(conf1.get(FlinkOptions.PRE_COMBINE), is(true)); // ...
public byte[] getSignature() { return signature; }
@Test public void testGetSignaure() { assertEquals(TestParameters.VP_CONTROL_DATA_SIGNATURE.getBytes(UTF_8).length, chmLzxcControlData.getSignature().length); }
public String name() { return name; }
@Test public void testConstruction() { assertThat(name1.name(), is(NAME1)); }
@Override public Iterator<Map.Entry<String, Object>> iterator() { return map.entrySet().iterator(); }
@Test public void oneProperty() { map.put("key", "value"); CamelMessagingHeadersExtractAdapter adapter = new CamelMessagingHeadersExtractAdapter(map, true); Iterator<Map.Entry<String, Object>> iterator = adapter.iterator(); Map.Entry<String, Object> entry = iterator.next(); a...
@Deprecated public String idFromFilename(@NonNull String filename) { return filename; }
@SuppressWarnings("deprecation") @Test public void caseSensitive() { IdStrategy idStrategy = new IdStrategy.CaseSensitive(); assertRestrictedNames(idStrategy); assertThat(idStrategy.idFromFilename("foo"), is("foo")); assertThat(idStrategy.idFromFilename("~foo"), is("Foo")); ...
@Bean("ComputationTempFolder") public TempFolder provide(ServerFileSystem fs) { File tempDir = new File(fs.getTempDir(), "ce"); try { FileUtils.forceMkdir(tempDir); } catch (IOException e) { throw new IllegalStateException("Unable to create computation temp directory " + tempDir, e); } ...
@Test public void existing_temp_dir() throws Exception { ServerFileSystem fs = mock(ServerFileSystem.class); File tmpDir = temp.newFolder(); when(fs.getTempDir()).thenReturn(tmpDir); TempFolder folder = underTest.provide(fs); assertThat(folder).isNotNull(); File newDir = folder.newDir(); ...
public boolean isRetryBranch() { return retryBranch; }
@Test public void testIsRetryBranch() { // Test the isSuccess method assertFalse(event.isRetryBranch()); }
public <T> T create(Class<T> clazz) { return create(clazz, new Class<?>[]{}, new Object[]{}); }
@Test void testProxyWorks() throws Exception { final SessionDao sessionDao = new SessionDao(sessionFactory); final UnitOfWorkAwareProxyFactory unitOfWorkAwareProxyFactory = new UnitOfWorkAwareProxyFactory("default", sessionFactory); final OAuthAuthenticator oAuthAuthenticato...
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException( "The level of the root logger cannot be set to null"); } level = newLevel; if (newLe...
@Test public void setRootLevelToNull() { try { root.setLevel(null); fail("The level of the root logger should not be settable to null"); } catch (IllegalArgumentException e) { } }
@Description("round to integer by dropping digits after decimal point") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double truncate(@SqlType(StandardTypes.DOUBLE) double num) { return Math.signum(num) * Math.floor(Math.abs(num)); }
@Test public void testTruncate() { // DOUBLE final String maxDouble = Double.toString(Double.MAX_VALUE); final String minDouble = Double.toString(-Double.MAX_VALUE); assertFunction("truncate(17.18E0)", DOUBLE, 17.0); assertFunction("truncate(-17.18E0)", DOUBLE, -17.0); ...
public static String getInterfaceName(Invoker invoker) { return getInterfaceName(invoker, false); }
@Test public void testGetInterfaceNameWithGroupAndVersion() throws NoSuchMethodException { URL url = URL.valueOf("dubbo://127.0.0.1:2181") .addParameter(CommonConstants.VERSION_KEY, "1.0.0") .addParameter(CommonConstants.GROUP_KEY, "grp1") .addParameter(Commo...
public void merge(HllBuffer buffer1, HllBuffer buffer2) { int idx = 0; int wordOffset = 0; while (wordOffset < numWords) { long word1 = buffer1.array[wordOffset]; long word2 = buffer2.array[wordOffset]; long word = 0L; int i = 0; long m...
@Test public void testMerge() { HyperLogLogPlusPlus hll = new HyperLogLogPlusPlus(0.05); HllBuffer buffer1a = createHllBuffer(hll); HllBuffer buffer1b = createHllBuffer(hll); HllBuffer buffer2 = createHllBuffer(hll); // Create the // Add the lower half int i ...
public static IUser normalizeUserInfo( IUser user ) { user.setLogin( user.getLogin().trim() ); user.setName( user.getName().trim() ); return user; }
@Test public void normalizeUserInfo_WithSpaces() { IUser normalized = RepositoryCommonValidations.normalizeUserInfo( user( " login \t\n ", "name" ) ); assertEquals( "login", normalized.getLogin() ); assertEquals( "login", normalized.getName() ); }
@VisibleForTesting public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics) { if (rowCount == 0) { return Domain.none(type); } if (columnStatistics == null) { return Domain.all(type); } if (columnStatistics.hasN...
@Test public void testChar() { assertEquals(getDomain(CHAR, 0, null), Domain.none(CHAR)); assertEquals(getDomain(CHAR, 10, null), Domain.all(CHAR)); assertEquals(getDomain(CHAR, 0, stringColumnStats(null, null, null)), Domain.none(CHAR)); assertEquals(getDomain(CHAR, 0, stringCo...
public static int chineseToNumber(String chinese) { final int length = chinese.length(); int result = 0; // 节总和 int section = 0; int number = 0; ChineseUnit unit = null; char c; for (int i = 0; i < length; i++) { c = chinese.charAt(i); final int num = chineseToNumber(c); if (num >= 0) { if...
@Test public void chineseToNumberTest() { assertEquals(0, NumberChineseFormatter.chineseToNumber("零")); assertEquals(102, NumberChineseFormatter.chineseToNumber("一百零二")); assertEquals(112, NumberChineseFormatter.chineseToNumber("一百一十二")); assertEquals(1012, NumberChineseFormatter.chineseToNumber("一千零一十二")); ...
public synchronized CryptoKey getOrCreateCryptoKey(String keyRingId, String keyName) { // Get the keyring, creating it if it does not already exist if (keyRing == null) { maybeCreateKeyRing(keyRingId); } try (KeyManagementServiceClient client = clientFactory.getKMSClient()) { // Build the...
@Test public void testGetOrCreateCryptoKeyShouldNotCreateCryptoKeyWhenItAlreadyExists() { String keyRingName = KeyRingName.of(PROJECT_ID, REGION, KEYRING_ID).toString(); KeyRing keyRing = KeyRing.newBuilder().setName(keyRingName).build(); CryptoKey cryptoKey = CryptoKey.newBuilder() .s...
@Override public ExampleTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) { if (!listSchemaNames(session).contains(tableName.getSchemaName())) { return null; } ExampleTable table = exampleClient.getTable(tableName.getSchemaName(), tableName.getT...
@Test public void testGetTableHandle() { assertEquals(metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")), NUMBERS_TABLE_HANDLE); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("example", "unknown"))); assertNull(metadata.getTableHandle(SESSION, n...
public static void hasText(String text, String message) { if (!StringUtil.hasText(text)) { throw new IllegalArgumentException(message); } }
@Test(expected = IllegalArgumentException.class) public void assertHasText() { Assert.hasText(" ", "text is null"); }
public Lease acquire() throws Exception { String path = internals.attemptLock(-1, null, null); return makeLease(path); }
@Test public void testClientClose() throws Exception { final Timing timing = new Timing(); CuratorFramework client1 = null; CuratorFramework client2 = null; InterProcessSemaphoreV2 semaphore1; InterProcessSemaphoreV2 semaphore2; try { client1 = CuratorFram...
public static void assertThatClassIsUtility(Class<?> clazz) { final UtilityClassChecker checker = new UtilityClassChecker(); if (!checker.isProperlyDefinedUtilityClass(clazz)) { final Description toDescription = new StringDescription(); final Description mismatchDescription = new...
@Test public void testFinalNoConstructorClass() throws Exception { boolean gotException = false; try { assertThatClassIsUtility(FinalNoConstructor.class); } catch (AssertionError assertion) { assertThat(assertion.getMessage(), containsString("class...
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about_menu_option: Navigation.findNavController(requireView()) .navigate(MainFragmentDirections.actionMainFragmentToAboutAnySoftKeyboardFragment()); return true; case R.id....
@Test public void testBackupMenuItem() throws Exception { final MainFragment fragment = startFragment(); final FragmentActivity activity = fragment.getActivity(); Menu menu = Shadows.shadowOf(activity).getOptionsMenu(); Assert.assertNotNull(menu); final MenuItem item = menu.findItem(R.id.backup_p...
public static Mode parse(String value) { if (StringUtils.isBlank(value)) { throw new IllegalArgumentException(ExceptionMessage.INVALID_MODE.getMessage(value)); } try { return parseNumeric(value); } catch (NumberFormatException e) { // Treat as symbolic return parseSymbolic(value...
@Test public void symbolicsPartial() { Mode parsed = ModeParser.parse("u=rwx"); assertEquals(Mode.Bits.ALL, parsed.getOwnerBits()); assertEquals(Mode.Bits.NONE, parsed.getGroupBits()); assertEquals(Mode.Bits.NONE, parsed.getOtherBits()); parsed = ModeParser.parse("go=rw"); assertEquals(Mode.B...
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@Test void testBasicArray2() { RichMapFunction<Boolean[], ?> function = new IdentityMapper<Boolean[]>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, BasicArrayTypeInfo.BOOLEAN_ARRAY_TYPE_INFO); assertThat(ti).isInstanceOf(Basic...
public static String getDynamicPropertiesAsString( Configuration baseConfig, Configuration targetConfig) { String[] newAddedConfigs = targetConfig.keySet().stream() .flatMap( (String key) -> { ...
@Test void testGetDynamicPropertiesAsString() { final Configuration baseConfig = new Configuration(); baseConfig.setString("key.a", "a"); baseConfig.setString("key.b", "b1"); final Configuration targetConfig = new Configuration(); targetConfig.setString("key.b", "b2"); ...
@Nonnull public static String removeBracketsFromIpv6Address(@Nonnull final String address) { final String result; if (address.startsWith("[") && address.endsWith("]")) { result = address.substring(1, address.length()-1); try { Ipv6.parse(result); ...
@Test public void stripBracketsIpv6() throws Exception { // Setup test fixture. final String input = "[0:0:0:0:0:0:0:1]"; // Execute system under test. final String result = AuthCheckFilter.removeBracketsFromIpv6Address(input); // Verify result. assertEquals("0:0:0:...
@Override public Object deserialize(Asn1ObjectInputStream in, Class<? extends Object> type, Asn1ObjectMapper mapper) { final Asn1Entity entity = type.getAnnotation(Asn1Entity.class); final Fields fields = new FieldSet(entity.partial(), mapper.getFields(type)); return readFields(mapper, in, f...
@Test public void shouldDeserialize() { assertEquals(new Set(1, 2), deserialize( new SetConverter(), Set.class, new byte[] { (byte) 0x81, 1, 0x01, (byte) 0x82, 1, 0x02 } )); }
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void withEmptryDefault() throws ScanException { Tokenizer tokenizer = new Tokenizer("${b:-}"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); witness.def...
public <E> ChainableFunction<E, T> after(Function<? super E, ? extends F> function) { return new ChainableFunction<E, T>() { @Override public T apply(E input) { return ChainableFunction.this.apply(function.apply(input)); } }; }
@Test public void after() { Integer result = plus(7).after(parseInteger()).apply("11"); assertThat(result).as("Adding 7 after parseInt('11')").isEqualTo(18); }
@Override public Column convert(BasicTypeDefine typeDefine) { try { return super.convert(typeDefine); } catch (SeaTunnelRuntimeException e) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefi...
@Test public void testConvertBlob() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("BLOB").dataType("BLOB").build(); Column column = KingbaseTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), col...
public static DnsServerAddresses rotational(Iterable<? extends InetSocketAddress> addresses) { return rotational0(sanitize(addresses)); }
@Test public void testRotational() { DnsServerAddresses seq = DnsServerAddresses.rotational(ADDR1, ADDR2, ADDR3); DnsServerAddressStream i = seq.stream(); assertNext(i, ADDR1); assertNext(i, ADDR2); assertNext(i, ADDR3); assertNext(i, ADDR1); assertNext(i, AD...
public static String[][] assignExecutors( List<? extends ScanTaskGroup<?>> taskGroups, List<String> executorLocations) { Map<Integer, JavaHash<StructLike>> partitionHashes = Maps.newHashMap(); String[][] locations = new String[taskGroups.size()][]; for (int index = 0; index < taskGroups.size(); index...
@TestTemplate public void testDataTasks() { List<ScanTask> tasks = ImmutableList.of( new MockDataTask(mockDataFile(Row.of(1, "a"))), new MockDataTask(mockDataFile(Row.of(2, "b"))), new MockDataTask(mockDataFile(Row.of(3, "c")))); ScanTaskGroup<ScanTask> taskGroup = ...
public static String[] getFieldFormatTypeCodes() { return fieldFormatTypeCodes; }
@Test public void testRoundTrip() throws KettleException { List<String> attributes = Arrays.asList( /*"connection",*/ "schema", "table", "encoding", "delimiter", "enclosure", "escape_char", "replace", "ignore", "local", "fifo_file_name", "bulk_size", "stream_name", "field_name", "field_form...
@NonNull public final Launcher decorateByEnv(@NonNull EnvVars _env) { final EnvVars env = new EnvVars(_env); final Launcher outer = this; return new Launcher(outer) { @Override public boolean isUnix() { return outer.isUnix(); } ...
@Issue("JENKINS-15733") @Test public void decorateByEnv() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); TaskListener l = new StreamBuildListener(baos, Charset.defaultCharset()); Launcher base = new Launcher.LocalLauncher(l); EnvVars env = new EnvVars("k...
@Override public ValueSet complement() { return new AllOrNoneValueSet(type, !all); }
@Test public void testComplement() { AllOrNoneValueSet all = AllOrNoneValueSet.all(HYPER_LOG_LOG); AllOrNoneValueSet none = AllOrNoneValueSet.none(HYPER_LOG_LOG); assertEquals(all.complement(), none); assertEquals(none.complement(), all); }
@Override public AbortTransactionResult abortTransaction(AbortTransactionSpec spec, AbortTransactionOptions options) { AdminApiFuture.SimpleAdminApiFuture<TopicPartition, Void> future = AbortTransactionHandler.newFuture(Collections.singleton(spec.topicPartition())); AbortTransactionHandl...
@Test public void testAbortTransaction() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { TopicPartition topicPartition = new TopicPartition("foo", 13); AbortTransactionSpec abortSpec = new AbortTransactionSpec( topicPartition, 12345L, (short) 1...
@Override public boolean test(final Path test) { return this.equals(new CaseSensitivePathPredicate(test)); }
@Test public void testPredicateTest() { final Path t = new Path("/f", EnumSet.of(Path.Type.file)); assertTrue(new CaseSensitivePathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.file)))); assertEquals(new CaseSensitivePathPredicate(t).hashCode(), new CaseSensitivePathPredicate(new Pat...
@Override public double calcDist3D(double fromY, double fromX, double fromHeight, double toY, double toX, double toHeight) { return sqrt(calcNormalizedDist(fromY, fromX, toY, toX) + calcNormalizedDist(toHeight - fromHeight)); }
@Test public void testDistance3dEuclidean() { DistanceCalcEuclidean distCalc = new DistanceCalcEuclidean(); assertEquals(1, distCalc.calcDist3D( 0, 0, 0, 0, 0, 1 ), 1e-6); assertEquals(10, distCalc.calcDist3D( 0, 0, 0, 0...
@Override public Decorator findById(String decoratorId) throws NotFoundException { final Decorator result = coll.findOneById(decoratorId); if (result == null) { throw new NotFoundException("Decorator with id " + decoratorId + " not found."); } return result; }
@Test public void findByIdThrowsIllegalArgumentExceptionForInvalidObjectId() throws NotFoundException { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("state should be: hexString has 24 characters"); decoratorService.findById("NOPE"); }
@Override public void start(Callback<None> callback) { LOG.info("{} enabled", _printName); Callback<None> prepareWarmUpCallback = new Callback<None>() { @Override public void onError(Throwable e) { if (e instanceof TimeoutException) { LOG.info("{} hit timeout: {}ms. The ...
@Test(retryAnalyzer = ThreeRetries.class) public void testNoMakingWarmUpRequestsWithoutWarmUp() throws URISyntaxException, InterruptedException, ExecutionException, TimeoutException { createDefaultServicesIniFiles(); TestLoadBalancer balancer = new TestLoadBalancer(); AtomicInteger requestCount = balan...
public static CheckResult mergeCheckResults(CheckResult... checkResults) { List<CheckResult> notPassConfig = Arrays.stream(checkResults) .filter(item -> !item.isSuccess()) .collect(Collectors.toList()); if (notPassConfig.isEmpty()) { ...
@Test public void testMergeCheckResults() { Config config = getConfig(); CheckResult checkResult1 = checkAllExists(config, "k0", "k1"); CheckResult checkResult2 = checkAtLeastOneExists(config, "k1", "k3"); CheckResult checkResult3 = checkAllExists(config, "k0", "k3"); CheckRe...
public static LayoutLocation fromCompactString(String s) { String[] tokens = s.split(COMMA); if (tokens.length != 4) { throw new IllegalArgumentException(E_BAD_COMPACT + s); } String id = tokens[0]; String type = tokens[1]; String latY = tokens[2]; Str...
@Test(expected = IllegalArgumentException.class) public void badCompactUnparsableY() { fromCompactString("foo,GEO,yyy,2.3"); }
public static MessageHeaders createAfnemersberichtAanDGLHeaders(Map<String, Object> additionalHeaders) { validateHeaders(additionalHeaders); Map<String, Object> headersMap = createBasicHeaderMap(); headersMap.put(nl.logius.digid.digilevering.lib.model.Headers.X_AUX_ACTION, "BRPAfnemersberichtAa...
@Test public void testSenderHeaderPresent() { Map<String, Object> map = new HashMap<>(); map.put(Headers.X_AUX_RECEIVER_ID, "receiverId"); assertThrows(IllegalArgumentException.class, () -> HeaderUtil.createAfnemersberichtAanDGLHeaders(map), "x_aux_sender_id sender header is mandatory"); ...
public boolean isDuplicateFilteringEnabled() { return filterDuplicates; }
@Test public void testDuplicateFilteringDisabledByDefault() { EpoxyController controller = new EpoxyController() { @Override protected void buildModels() { } }; assertFalse(controller.isDuplicateFilteringEnabled()); }
@Override public AlarmInfo ack(Alarm alarm, User user) throws ThingsboardException { return ack(alarm, System.currentTimeMillis(), user); }
@Test public void testAck() throws ThingsboardException { var alarm = new Alarm(); when(alarmSubscriptionService.acknowledgeAlarm(any(), any(), anyLong())) .thenReturn(AlarmApiCallResult.builder().successful(true).modified(true).alarm(new AlarmInfo()).build()); service.ack(al...
public static KTableHolder<GenericKey> build( final KGroupedStreamHolder groupedStream, final StreamAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedStream, aggregate, buildContext, ...
@Test public void shouldBuildValueSerdeCorrectlyForUnwindowedAggregate() { // Given: givenUnwindowedAggregate(); // When: aggregate.build(planBuilder, planInfo); // Then: verify(buildContext).buildValueSerde( VALUE_FORMAT, PHYSICAL_AGGREGATE_SCHEMA, MATERIALIZE_CTX ...
public static Timestamp toTimestamp(BigDecimal bigDecimal) { final BigDecimal nanos = bigDecimal.remainder(BigDecimal.ONE.scaleByPowerOfTen(9)); final BigDecimal seconds = bigDecimal.subtract(nanos).scaleByPowerOfTen(-9).add(MIN_SECONDS); return Timestamp.ofTimeSecondsAndNanos(seconds.longValue(), nanos.in...
@Test(expected = IllegalArgumentException.class) public void testToTimestampThrowsExceptionWhenThereIsAnUnderflow() { TimestampUtils.toTimestamp(BigDecimal.valueOf(-1L)); }
public static <T extends CharSequence> T[] removeEmpty(T[] array) { return filter(array, StrUtil::isNotEmpty); }
@Test public void removeEmptyTest() { String[] a = {"a", "b", "", null, " ", "c"}; String[] resultA = {"a", "b", " ", "c"}; assertArrayEquals(ArrayUtil.removeEmpty(a), resultA); }
@Override public void validateJoinRequest(JoinMessage joinMessage) { // check joining member's major.minor version is same as current cluster version's major.minor numbers MemberVersion memberVersion = joinMessage.getMemberVersion(); Version clusterVersion = node.getClusterService().getClust...
@Test public void test_joinRequestAllowed_whenNextPatchVersion() { MemberVersion nextPatchVersion = MemberVersion.of(nodeVersion.getMajor(), nodeVersion.getMinor(), nodeVersion.getPatch() + 1); JoinRequest joinRequest = new JoinRequest(Packet.VERSION, buildNumber, nextPatchVersion, j...
@ApiOperation(value = "List jobs", tags = { "Jobs" }, nickname = "listJobs") @ApiImplicitParams({ @ApiImplicitParam(name = "id", dataType = "string", value = "Only return job with the given id", paramType = "query"), @ApiImplicitParam(name = "processInstanceId", dataType = "string", value = ...
@Test @Deployment(resources = { "org/flowable/rest/service/api/management/JobCollectionResourceTest.testTimerProcess.bpmn20.xml" }) public void testGetJobs() throws Exception { Calendar hourAgo = Calendar.getInstance(); hourAgo.add(Calendar.HOUR, -1); Calendar inAnHour = Calendar.getIns...
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null)...
@Test public void testAlterOffsetsOffsetValues() { MirrorSourceConnector connector = new MirrorSourceConnector(); Function<Object, Boolean> alterOffsets = offset -> connector.alterOffsets(null, Collections.singletonMap( sourcePartition("t", 5, "backup"), Collections....
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return internalExecutor.schedule(command, delay, unit); }
@Test public void testSchedule() throws Exception { TestRunnable runnable = new TestRunnable(); ScheduledFuture<?> future = executionService.schedule(runnable, 0, SECONDS); Object result = future.get(); assertTrue(runnable.isExecuted()); assertNull(result); }
@Override public MetadataRequest.Builder buildRequest(Set<TopicPartition> partitions) { MetadataRequestData request = new MetadataRequestData(); request.setAllowAutoTopicCreation(false); partitions.stream().map(TopicPartition::topic).distinct().forEach(topic -> request.topics().a...
@Test public void testBuildLookupRequest() { Set<TopicPartition> topicPartitions = mkSet( new TopicPartition("foo", 0), new TopicPartition("bar", 0), new TopicPartition("foo", 1), new TopicPartition("baz", 0) ); PartitionLeaderStrategy strateg...
public static <T> Global<T> globally() { return new Global<>(); }
@Test @Category(NeedsRunner.class) public void testAggregateLogicalValuesGlobally() { Collection<BasicEnum> elements = Lists.newArrayList( BasicEnum.of("a", BasicEnum.TestEnum.ONE), BasicEnum.of("a", BasicEnum.TestEnum.TWO)); CombineFn<EnumerationType.Value, ?, Iterable<EnumerationType....
@CanIgnoreReturnValue public Caffeine<K, V> weakValues() { requireState(valueStrength == null, "Value strength was already set to %s", valueStrength); valueStrength = Strength.WEAK; return this; }
@Test public void weakValues() { var cache = Caffeine.newBuilder().weakValues().build(); assertThat(cache).isNotNull(); }
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) { Objects.requireNonNull(type, "type must not be null"); TypeAdapter<?> cached = typeTokenCache.get(type); if (cached != null) { @SuppressWarnings("unchecked") TypeAdapter<T> adapter = (TypeAdapter<T>) cached; return adapter; } ...
@Test public void testGetAdapter_Null() { Gson gson = new Gson(); NullPointerException e = assertThrows(NullPointerException.class, () -> gson.getAdapter((TypeToken<?>) null)); assertThat(e).hasMessageThat().isEqualTo("type must not be null"); }
public <T extends MongoEntity> MongoCollection<T> collection(String collectionName, Class<T> valueType) { return getCollection(collectionName, valueType); }
@Test void testBasicTypes() { final MongoCollection<Person> collection = collections.collection("people", Person.class); final Person person = new Person( "000000000000000000000001", "000000000000000000000002", new ObjectId("000000000000000000000003"),...
@Override public Object convertToPropertyType(Class<?> entityType, String[] propertyPath, String value) { IndexValueFieldDescriptor fieldDescriptor = getValueFieldDescriptor(entityType, propertyPath); if (fieldDescriptor == null) { return super.convertToPropertyType(entityType, propertyPath, val...
@Test public void testConvertLongProperty() { assertThat(convertToPropertyType(TestEntity.class, "l", "42")).isEqualTo(42L); }
@Override public long arraySize(String path) { return get(arraySizeAsync(path)); }
@Test public void testArraySize() { RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class)); TestType t = new TestType(); NestedType nt = new NestedType(); nt.setValues(Arrays.asList("t1", "t2", "t4")); t.setType(nt); al.set(t); ...
public static PDImageXObject createFromFile(String imagePath, PDDocument doc) throws IOException { return createFromFileByExtension(new File(imagePath), doc); }
@Test void testCreateFromFile() throws IOException, URISyntaxException { testCompareCreatedFileWithCreatedByCCITTFactory("ccittg4.tif"); testCompareCreatedFileWithCreatedByJPEGFactory("jpeg.jpg"); testCompareCreatedFileWithCreatedByJPEGFactory("jpegcmyk.jpg"); testCompareCreate...
public boolean isSuccess() { return isSuccess; }
@Test public void testIsSuccess() { result.setSuccess(true); assertTrue(result.isSuccess()); }
public static <T> RedistributeArbitrarily<T> arbitrarily() { return new RedistributeArbitrarily<>(null, false); }
@Test @Category(ValidatesRunner.class) public void testRedistributeAfterSessionsAndGroupByKey() { PCollection<KV<String, Iterable<Integer>>> input = pipeline .apply( Create.of(GBK_TESTABLE_KVS) .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())...
@Override @Nullable public User load(final String username) { LOG.debug("Loading user {}", username); // special case for the locally defined user, we don't store that in MongoDB. if (!configuration.isRootUserDisabled() && configuration.getRootUsername().equals(username)) { ...
@Test(expected = RuntimeException.class) @MongoDBFixtures("UserServiceImplTest.json") public void testLoadDuplicateUser() throws Exception { userService.load("user-duplicate"); }
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldNotErrorWhenConflictingUnreliableSessionSpecificSubscriptionAddedToDifferentSessionsVsWildcard() { final long id1 = driverProxy.addSubscription(CHANNEL_4000 + "|session-id=1024|reliable=false", STREAM_ID_1); driverConductor.doWork(); final long id2 = driverProxy.addSubs...
@Override public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space, Repository repository, IMetaStore metaStore ) { ...
@Test public void testCheck() { List<CheckResultInterface> remarks = new ArrayList<>(); JmsProducerMeta jmsProducerMeta = new JmsProducerMeta(); jmsProducerMeta.setDisableMessageId( "asdf" ); jmsProducerMeta.setDisableMessageTimestamp( "asdf" ); jmsProducerMeta.setDeliveryMode( "asdf" ); jmsPr...
static @Nullable <V> V getWhenSuccessful(@Nullable CompletableFuture<V> future) { try { return (future == null) ? null : future.join(); } catch (CancellationException | CompletionException e) { return null; } }
@Test public void getWhenSuccessful_success_async() { var future = new CompletableFuture<Integer>(); var result = new AtomicInteger(); ConcurrentTestHarness.execute(() -> { result.set(1); result.set(Async.getWhenSuccessful(future)); }); await().untilAtomic(result, is(1)); future.co...
public Collection<ServerPluginInfo> loadPlugins() { Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>(); for (ServerPluginInfo bundled : getBundledPluginsMetadata()) { failIfContains(bundledPluginsByKey, bundled, plugin -> MessageException.of(format("Found two versions of the...
@Test public void fail_if_bundled_plugins_have_same_key() throws IOException { File jar1 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); File jar2 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledBundledPluginsDir())...