focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean hasGlobalAdminRole(String username) { return roleService.hasGlobalAdminRole(username); }
@Test void testHasGlobalAdminRole3() { NacosUser nacosUser = new NacosUser("nacos"); nacosUser.setGlobalAdmin(true); boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser); assertTrue(hasGlobalAdminRole); }
public static Thread daemonThread(Runnable r, Class<?> context, String description) { return daemonThread(r, "hollow", context, description); }
@Test public void named() { Thread thread = daemonThread(() -> {}, "Thready McThreadson"); assertEquals("Thready McThreadson", thread.getName()); assertTrue(thread.isDaemon()); // TODO(timt): invariant }
public Integer doCall() throws Exception { List<Row> rows = new ArrayList<>(); List<Integration> integrations = client(Integration.class).list().getItems(); integrations .forEach(integration -> { Row row = new Row(); row.name = integration...
@Test public void shouldListReadyIntegration() throws Exception { Integration integration = createIntegration(); IntegrationStatus status = new IntegrationStatus(); IntegrationKit kit = new IntegrationKit(); kit.setName("kit-123456789"); status.setIntegrationKit(kit); ...
public boolean tableNotExistsOrDoesNotMatchSpecification(String tableName) { TableId tableId = TableId.of(projectId, datasetName, tableName); Table table = bigquery.getTable(tableId); if (table == null || !table.exists()) { return true; } ExternalTableDefinition externalTableDefinition = table...
@Test void testTableNotExistsOrDoesNotMatchSpecification() { BigQuerySyncConfig config = new BigQuerySyncConfig(properties); client = new HoodieBigQuerySyncClient(config, mockBigQuery); // table does not exist assertTrue(client.tableNotExistsOrDoesNotMatchSpecification(TEST_TABLE)); TableId table...
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { if ( dbMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) ); } ...
@Test( expected = KettleDatabaseException.class ) public void testGetLegacyColumnNameNullDBMetaDataException() throws Exception { new MySQLDatabaseMeta().getLegacyColumnName( null, getResultSetMetaData(), 1 ); }
public static boolean isEIP3668(String data) { if (data == null || data.length() < 10) { return false; } return EnsUtils.EIP_3668_CCIP_INTERFACE_ID.equals(data.substring(0, 10)); }
@Test void isEIP3668WhenSuccess() { assertTrue(EnsUtils.isEIP3668(EnsUtils.EIP_3668_CCIP_INTERFACE_ID + "some data")); }
@Override public HttpResponse send(HttpRequest httpRequest) throws IOException { return send(httpRequest, null); }
@Test public void send_whenInvalidCertificatesAreIgnored_getResponseWithoutException() throws GeneralSecurityException, IOException { InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); String host = "host.com"; MockWebServer mockWebServer = startMockWebServerWithSsl(loopbackAddress); ...
@Override @MethodNotAvailable public boolean evict(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testEvict() { adapter.evict(23); }
@CheckReturnValue @NonNull public static Observable<Boolean> observePowerSavingState( @NonNull Context context, @StringRes int enablePrefResId, @BoolRes int defaultValueResId) { final RxSharedPrefs prefs = AnyApplication.prefs(context); return Observable.combineLatest( prefs ...
@Test public void testAlwaysPowerSavingMode() { SharedPrefsHelper.setPrefsValue(R.string.settings_key_power_save_mode, "always"); AtomicReference<Boolean> state = new AtomicReference<>(null); final Observable<Boolean> powerSavingState = PowerSaving.observePowerSavingState(getApplicationContext(),...
@Override protected String getRootKey() { return Constants.HEADER_GCS + mBucketName; }
@Test public void testGetRootKey() { Assert.assertEquals(Constants.HEADER_GCS + BUCKET_NAME, mGCSUnderFileSystem.getRootKey()); }
@Override public long get(long key1, long key2) { return super.get0(key1, key2); }
@Test public void testGotoAddress() { final long addr1 = hsa.address(); final SlotAssignmentResult slot = insert(1, 2); hsa.gotoNew(); assertEquals(NULL_ADDRESS, hsa.get(1, 2)); hsa.gotoAddress(addr1); assertEquals(slot.address(), hsa.get(1, 2)); }
public void computeCpd(Component component, Collection<Block> originBlocks, Collection<Block> duplicationBlocks) { CloneIndex duplicationIndex = new PackedMemoryCloneIndex(); populateIndex(duplicationIndex, originBlocks); populateIndex(duplicationIndex, duplicationBlocks); List<CloneGroup> duplications...
@Test public void default_minimum_tokens_is_one_hundred() { settings.setProperty("sonar.cpd.xoo.minimumTokens", (Integer) null); Collection<Block> originBlocks = singletonList( new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) ....
public Collection<String> getRelatedShadowTables(final Collection<String> tableNames) { Collection<String> result = new LinkedList<>(); for (String each : tableNames) { if (shadowTableRules.containsKey(each)) { result.add(each); } } return result; ...
@Test void assertGetRelatedShadowTables() { Collection<String> relatedShadowTables = shadowRule.getRelatedShadowTables(Arrays.asList("t_user", "t_auto")); assertThat(relatedShadowTables.size(), is(1)); assertThat(relatedShadowTables.iterator().next(), is("t_user")); }
public LagFunction(List<Integer> argumentChannels) { this.valueChannel = argumentChannels.get(0); this.offsetChannel = (argumentChannels.size() > 1) ? argumentChannels.get(1) : -1; this.defaultChannel = (argumentChannels.size() > 2) ? argumentChannels.get(2) : -1; }
@Test public void testLagFunction() { assertWindowQuery("lag(orderdate) OVER (PARTITION BY orderstatus ORDER BY orderkey)", resultBuilder(TEST_SESSION, INTEGER, VARCHAR, VARCHAR) .row(3, "F", null) .row(5, "F", "1993-10-14") ...
@Override public V fetch(final K key, final long time) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (final ReadOnlyWindowStore<K, V> windowStore : stores) { try { ...
@Test public void emptyIteratorNextShouldThrowNoSuchElementException() { final StateStoreProvider storeProvider = mock(StateStoreProvider.class); when(storeProvider.stores(anyString(), any())).thenReturn(emptyList()); final CompositeReadOnlyWindowStore<Object, Object> store = new CompositeR...
@Override public FileInfo generateClientFileInfo(String path) { FileInfo ret = new FileInfo(); ret.setFileId(getId()); ret.setName(getName()); ret.setPath(path); ret.setBlockSizeBytes(0); ret.setCreationTimeMs(getCreationTimeMs()); ret.setCompleted(true); ret.setFolder(isDirectory()); ...
@Test public void generateClientFileInfo() { MutableInodeDirectory inodeDirectory = createInodeDirectory(); String path = "/test/path"; FileInfo info = inodeDirectory.generateClientFileInfo(path); Assert.assertEquals(inodeDirectory.getId(), info.getFileId()); Assert.assertEquals(inodeDirectory.get...
@Override public void addSlots(Collection<AllocatedSlot> slots, long currentTime) { for (AllocatedSlot slot : slots) { addSlot(slot, currentTime); } }
@Test void testAddSlots() { final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool(); final Collection<AllocatedSlot> slots = createAllocatedSlots(); slotPool.addSlots(slots, 0); assertSlotPoolContainsSlots(slotPool, slots); assertSlotPoolContainsFreeSlots(...
@Nonnull public static String replaceRange(@Nonnull String string, int start, int end, String replacement) { String temp = string.substring(0, start); temp += replacement; temp += string.substring(end); return temp; }
@Test void testReplaceRange() { assertEquals("_cdefg", StringUtil.replaceRange("abcdefg", 0, 2, "_")); }
public static String format(double amount, boolean isUseTraditional) { return format(amount, isUseTraditional, false); }
@Test public void formatTenThousandLongTest() { String f = NumberChineseFormatter.format(1_0000, false); assertEquals("一万", f); f = NumberChineseFormatter.format(1_0001, false); assertEquals("一万零一", f); f = NumberChineseFormatter.format(1_0010, false); assertEquals("一万零一十", f); f = NumberChineseFormatter...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void zeroMinimumNumberOfCallsShouldFail() { custom().slidingWindow(2, 0, SlidingWindowType.COUNT_BASED).build(); }
@Override public V put(@Nullable final K key, final V value) { if (key == null) { if (nullEntry == null) { _size += 1; nullEntry = new Entry<>(null, value); return null; } return nullEntry.setValue(value); } ...
@Test public void testPutGet() { final Map<Integer, String> tested = new HashMap<>(); for (int i = 0; i < 1000; ++i) { tested.put(i, Integer.toString(i)); } tested.put(null, "null"); Assert.assertEquals(1001, tested.size()); for (int i = 0; i < 1000; ++i) ...
public static NamespaceName get(String tenant, String namespace) { validateNamespaceName(tenant, namespace); return get(tenant + '/' + namespace); }
@Test(expectedExceptions = IllegalArgumentException.class) public void namespace_emptyTenant() { NamespaceName.get("", "cluster", "namespace"); }
@Override public void open() throws Exception { this.timerService = getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this); this.keySet = new HashSet<>(); super.open(); }
@Test void testKeyCheck() throws Exception { OutputTag<Long> sideOutputTag = new OutputTag<Long>("side-output") {}; AtomicBoolean emitToFirstOutput = new AtomicBoolean(true); KeyedTwoOutputProcessOperator<Integer, Integer, Integer, Long> processOperator = new KeyedTwoOutputPr...
public static Object get(Object object, int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } if (object instanceof Map) { Map map = (Map) object; Iterator iterator = map.entrySet().iterator(); r...
@Test void testGetArray3() { assertEquals("1", CollectionUtils.get(new Object[] {"1"}, 0)); assertEquals("2", CollectionUtils.get(new Object[] {"1", "2"}, 1)); }
public static List<TargetInfo> parseOptTarget(CommandLine cmd, AlluxioConfiguration conf) throws IOException { String[] targets; if (cmd.hasOption(TARGET_OPTION_NAME)) { String argTarget = cmd.getOptionValue(TARGET_OPTION_NAME); if (StringUtils.isBlank(argTarget)) { throw new IOExcepti...
@Test public void parseSingleMasterTarget() throws Exception { mConf.set(PropertyKey.MASTER_HOSTNAME, "masters-1"); CommandLine mockCommandLine = mock(CommandLine.class); String[] mockArgs = new String[]{"--target", "master"}; when(mockCommandLine.getArgs()).thenReturn(mockArgs); when(mockCommand...
@Override public V remove() { return removeFirst(); }
@Test public void testRemoveEmpty() { Assertions.assertThrows(NoSuchElementException.class, () -> { RQueue<Integer> queue = getQueue(); queue.remove(); }); }
public void onHttpServerUpgrade(Http2Settings settings) throws Http2Exception { if (!connection().isServer()) { throw connectionError(PROTOCOL_ERROR, "Server-side HTTP upgrade requested for a client"); } if (!prefaceSent()) { // If the preface was not sent yet it most lik...
@Test public void onHttpServerUpgradeWithoutHandlerAdded() throws Exception { handler = new Http2ConnectionHandlerBuilder().frameListener(new Http2FrameAdapter()).server(true).build(); Http2Exception e = assertThrows(Http2Exception.class, new Executable() { @Override public v...
public void replicaBackupLog(List<TransactionLogRecord> records, UUID callerUuid, UUID txnId, long timeoutMillis, long startTime) { TxBackupLog beginLog = txBackupLogs.get(txnId); if (beginLog == null) { throw new TransactionException("Could not find begin tx...
@Test(expected = TransactionException.class) public void replicaBackupLog_whenNotExist_thenTransactionException() { List<TransactionLogRecord> records = new LinkedList<>(); txService.replicaBackupLog(records, UuidUtil.newUnsecureUUID(), TXN, 1, 1); }
@Override public String generateSqlType(Dialect dialect) { switch (dialect.getId()) { case MsSql.ID: return "NVARCHAR (MAX)"; case Oracle.ID, H2.ID: return "CLOB"; case PostgreSql.ID: return "TEXT"; default: throw new IllegalArgumentException("Unsupported di...
@Test public void generate_sql_type_on_oracle() { assertThat(underTest.generateSqlType(new Oracle())).isEqualTo("CLOB"); }
public static WebSocketUpstream buildWebSocketUpstream(final String protocol, final String host, final Integer port) { return WebSocketUpstream.builder().host(LOCALHOST).protocol(protocol) .upstreamUrl(buildUrl(host, port)).weight(DEFAULT_WEIGHT) .warmup(Constants.WARMUP_TIME) ...
@Test public void buildWebSocketUpstream() { WebSocketUpstream webSocketUpstream = CommonUpstreamUtils.buildWebSocketUpstream("tcp", HOST, PORT); Assert.assertNotNull(webSocketUpstream); Assert.assertEquals(HOST + ":" + PORT, webSocketUpstream.getUpstreamUrl()); Assert.assertEquals("...
@Override public void upgrade() { try { streamService.load(Stream.DEFAULT_STREAM_ID); } catch (NotFoundException ignored) { createDefaultStream(); } }
@Test public void upgradeDoesNotRunIfDefaultStreamExists() throws Exception { when(streamService.load("000000000000000000000001")).thenReturn(mock(Stream.class)); migration.upgrade(); verify(streamService, never()).save(any(Stream.class)); }
public static String gensalt(int log_rounds, SecureRandom random) { StringBuffer rs = new StringBuffer(); byte rnd[] = new byte[BCRYPT_SALT_LEN]; random.nextBytes(rnd); rs.append("$2a$"); if (log_rounds < 10) rs.append("0"); if (log_rounds > 30) {...
@Test public void testGensalt() { System.out.print("BCrypt.gensalt(): "); for (int i = 0; i < test_vectors.length; i += 4) { String plain = test_vectors[i][0]; String salt = BCrypt.gensalt(); String hashed1 = BCrypt.hashpw(plain, salt); String has...
@Override public long getPriority( TieredStoragePartitionId partitionId, TieredStorageSubpartitionId subpartitionId, int segmentId, int bufferIndex, @Nullable ReadProgress readProgress) throws IOException { // noop return -1; ...
@Test void testGetPriority() throws IOException { assertThat( partitionFileReader.getPriority( DEFAULT_PARTITION_ID, DEFAULT_SUBPARTITION_ID, 0, 0, null)) .isEqualTo(-1); assertThat(readBuffer(0, DEFAULT_SUBPARTITION_ID, 0)).isN...
public static String toHivePartitionName(List<String> partitionColumnNames, PartitionKey partitionKey) { List<String> partitionValues = fromPartitionKey(partitionKey); return toHivePartitionName(partitionColumnNames, partitionValues); }
@Test public void testHivePartitionNames() { List<String> partitionValues = Lists.newArrayList("1", "2", "3"); String partitionNames = "a=1/b=2/c=3"; HivePartitionName hivePartitionName = new HivePartitionName("db", "table", partitionValues, Optional.of(partitionNames)); ...
public void sendCouponNewsletter() { try { // Retrieve the list of contacts from the "weekly-coupons-newsletter" contact // list // snippet-start:[sesv2.java2.newsletter.ListContacts] ListContactsRequest contactListRequest = ListContactsRequest.builder() .contactListName(CONTACT_LI...
@Test public void test_sendCouponNewsletter_error_sendingPaused() { // Mock the necessary AWS SDK calls and responses CreateEmailTemplateResponse templateResponse = CreateEmailTemplateResponse.builder().build(); when(sesClient.createEmailTemplate(any(CreateEmailTemplateRequest.class))).thenReturn(template...
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j ...
@Test public void testNonConformantPath() { Map<String, String> res = resolveVariables("{cachemanager}-{cache}", "default"); assertEquals(0, res.size()); }
public <T extends VFSConnectionDetails> boolean test( @NonNull ConnectionManager manager, @NonNull T details, @Nullable VFSConnectionTestOptions options ) throws KettleException { if ( options == nul...
@Test public void testTestReturnsFalseWhenRootPathHasInvalidRelativeSegments() throws KettleException { when( vfsConnectionDetails.getRootPath() ).thenReturn( "../other-connection" ); assertFalse( vfsConnectionManagerHelper.test( connectionManager, vfsConnectionDetails, getTestOptionsCheckRootPath() ) ); ...
@VisibleForTesting List<MessageSummary> getMessageBacklog(EventNotificationContext ctx, SlackEventNotificationConfig config) { List<MessageSummary> backlog = notificationCallbackService.getBacklogForEvent(ctx); if (config.backlogSize() > 0 && backlog != null) { return backlog.stream().li...
@Test public void testBacklogMessageLimitWhenEventNotificationContextIsNull() { SlackEventNotificationConfig slackConfig = SlackEventNotificationConfig.builder() .backlogSize(0) .build(); //global setting is at N and the eventNotificationContext is null then the mess...
public static Ip6Address valueOf(byte[] value) { return new Ip6Address(value); }
@Test public void testValueOfInetAddressIPv6() { Ip6Address ipAddress; InetAddress inetAddress; inetAddress = InetAddresses.forString("1111:2222:3333:4444:5555:6666:7777:8888"); ipAddress = Ip6Address.valueOf(inetAddress); assertThat(ipAddress.toString(), ...
public static Deserializer<RouterSolicitation> deserializer() { return (data, offset, length) -> { checkInput(data, offset, length, HEADER_LENGTH); RouterSolicitation routerSolicitation = new RouterSolicitation(); ByteBuffer bb = ByteBuffer.wrap(data, offset, length); ...
@Test public void testDeserializeBadInput() throws Exception { PacketTestUtils.testDeserializeBadInput(RouterSolicitation.deserializer()); }
@Override public V merge(String key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return Map.super.merge(key.toLowerCase(), value, remappingFunction); }
@Test void merge() { Map<String, Object> map = new LowerCaseLinkHashMap<>(lowerCaseLinkHashMap); Object result = map.merge("key", "merge",(oldValue,value)-> oldValue.toString().toUpperCase()); Assertions.assertEquals("VALUE", result); Assertions.assertEquals("VALUE", map.get("key"));...
public Struct put(String fieldName, Object value) { Field field = lookupField(fieldName); return put(field, value); }
@Test public void testInvalidStructFieldValue() { assertThrows(DataException.class, () -> new Struct(NESTED_SCHEMA).put("nested", new Struct(NESTED_CHILD_SCHEMA))); }
public static int getAvailablePort(String host, int port) { return getAvailablePort(host, port, MAX_PORT); }
@Test public void getAvailablePort() throws Exception { int port = NetUtils.getAvailablePort("127.0.0.1", 33000); Assert.assertTrue(port >= 33000 && port < 65535); port = NetUtils.getAvailablePort("0.0.0.0", 33000); Assert.assertTrue(port >= 33000 && port < 65535); port = Net...
public int computeThreshold(StreamConfig streamConfig, CommittingSegmentDescriptor committingSegmentDescriptor, @Nullable SegmentZKMetadata committingSegmentZKMetadata, String newSegmentName) { long desiredSegmentSizeBytes = streamConfig.getFlushThresholdSegmentSizeBytes(); if (desiredSegmentSizeBytes <= ...
@Test public void testApplyMultiplierToAdjustedTotalDocsWhenTimeThresholdIsReached() { long currentTime = 1640216032391L; Clock clock = Clock.fixed(java.time.Instant.ofEpochMilli(currentTime), ZoneId.of("UTC")); SegmentFlushThresholdComputer computer = new SegmentFlushThresholdComputer(clock); Strea...
@Override public String buildContext() { final String plugins = ((Collection<?>) getSource()) .stream() .map(s -> ((PluginDO) s).getName()) .collect(Collectors.joining(",")); return String.format("the plugins[%s] is %s", plugins, StringUtils.lowerCase(...
@Test public void batchChangePluginBuildContextTest() { String context = String.format("the plugins[%s] is %s", "test-plugin,test-plugin-two", EventTypeEnum.PLUGIN_UPDATE.getType().toString().toLowerCase()); assertEquals(context, changedEvent.buildContext()); }
@Bean public PluginDataHandler springCloudPluginDataHandler(final ObjectProvider<DiscoveryClient> discoveryClient, final ShenyuConfig shenyuConfig) { return new SpringCloudPluginDataHandler(discoveryClient.getIfAvailable(), shenyuConfig.getSpringClou...
@Test public void testSpringCloudPluginDataHandler() { applicationContextRunner.run(context -> { PluginDataHandler handler = context.getBean("springCloudPluginDataHandler", PluginDataHandler.class); assertNotNull(handler); } ); }
private RFuture<Boolean> trySet(V newValue, BucketTrySetOperation operation) { checkState(); return executeLocked(() -> { if (state != null) { operations.add(operation); if (state == NULL) { state = Optional.ofNullable((Object) newValue).or...
@Test public void testTrySet() { RBucket<String> b = redisson.getBucket("test"); b.set("123"); RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults()); RBucket<String> bucket = transaction.getBucket("test"); assertThat(bucket.trySet("0"))...
@Override public void write(final PostgreSQLPacketPayload payload, final Object value) { payload.getByteBuf().writeFloat(Float.parseFloat(value.toString())); }
@Test void assertWrite() { new PostgreSQLFloatBinaryProtocolValue().write(new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8), 1F); verify(byteBuf).writeFloat(1.0F); }
@SuppressWarnings("ConstantConditions") public boolean addOrReplaceAction(@NonNull Action a) { if (a == null) { throw new IllegalArgumentException("Action must be non-null"); } // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way: List<Actio...
@Test public void addOrReplaceAction_null() { assertThrows(IllegalArgumentException.class, () -> thing.addOrReplaceAction(null)); }
String lowercase(String string) { string = string.toLowerCase(); return string; }
@Test void test() { FullyCovered fullyCovered = new FullyCovered(); String string = fullyCovered.lowercase("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); }
public boolean overlap(final Window other) throws IllegalArgumentException { if (getClass() != other.getClass()) { throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type " + other.getClass() + "."); } final SessionWindow ot...
@Test public void shouldNotOverlapIsOtherWindowIsAfterThisWindow() { /* * This: [-------] * Other: [---] */ assertFalse(window.overlap(new SessionWindow(end + 1, end + 1))); assertFalse(window.overlap(new SessionWindow(end + 1, 150))); ...
public static int hash(Object o) { if (o == null) { return 0; } if (o instanceof Long) { return hashLong((Long) o); } if (o instanceof Integer) { return hashLong((Integer) o); } if (o instanceof Double) { return hash...
@Test public void testHashByteArrayOverload() { String input = "hashthis"; byte[] inputBytes = input.getBytes(); int hashOfString = MurmurHash.hash(input); assertEquals("MurmurHash.hash(byte[]) did not match MurmurHash.hash(String)", hashOfString, MurmurHash.has...
public static boolean isMatch(String regex, CharSequence content) { if (content == null) { // 提供null的字符串为不匹配 return false; } if (StrUtil.isEmpty(regex)) { // 正则不存在则为全匹配 return true; } // Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); final Pattern pattern = PatternPool.get(regex, Pa...
@Test public void isMatchTest() { // 给定字符串是否匹配给定正则 final boolean isMatch = ReUtil.isMatch("\\w+[\u4E00-\u9FFF]+\\d+", content); assertTrue(isMatch); }
@Override public LoggingRuleConfiguration build() { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if ("ch.qos.logback.classic.LoggerContext".equals(iLoggerFactory.getClass().getName())) { LoggerContext loggerContext = (LoggerContext) iLoggerFactory; retur...
@Test void assertBuild() { LoggingRuleConfiguration actual = new DefaultLoggingRuleConfigurationBuilder().build(); assertThat(actual.getLoggers().size(), is(4)); assertThat(actual.getAppenders().size(), is(1)); }
public CompiledPipeline.CompiledExecution buildExecution() { return buildExecution(false); }
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void compilerBenchmark() throws Exception { final PipelineIR baselinePipelineIR = createPipelineIR(200); final PipelineIR testPipelineIR = createPipelineIR(400); final JrubyEventExtLibrary.RubyEvent testEvent = Jru...
public B listener(String listener) { this.listener = listener; return getThis(); }
@Test void listener() { InterfaceBuilder builder = new InterfaceBuilder(); builder.listener("mockinvokerlistener"); Assertions.assertEquals("mockinvokerlistener", builder.build().getListener()); }
public void updateNodeResource(RMNode nm, ResourceOption resourceOption) { writeLock.lock(); try { SchedulerNode node = getSchedulerNode(nm.getNodeID()); if (node == null) { LOG.info("Node: " + nm.getNodeID() + " has already been taken out of " + "scheduling. Skip updating ...
@Test public void testMaxAllocationAfterUpdateNodeResource() throws IOException { final int configuredMaxVCores = 20; final int configuredMaxMemory = 10 * 1024; Resource configuredMaximumResource = Resource.newInstance (configuredMaxMemory, configuredMaxVCores); YarnConfiguration conf = getCo...
@Override public boolean registerAllRequestsProcessedListener(NotificationListener listener) throws IOException { return super.registerAllRequestsProcessedListener(listener); }
@Test void testConcurrentSubscribeAndHandleRequest() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(2); final TestNotificationListener listener = new TestNotificationListener(); final Callable<Boolean> subscriber = () -> writer.registerAllR...
public boolean isOlderThan(Object obj) { if (obj instanceof VersionNumber) { return compareTo((VersionNumber) obj) < 0; } return false; }
@Test void testIsOlderThan() { assertThat(v("5.0.0").isOlderThan(v("6.0.0"))).isTrue(); assertThat(v("9.0.0").isOlderThan(v("10.0.0"))).isTrue(); assertThat(v("1.0.0").isOlderThan(v("10.0.0"))).isTrue(); assertThat(v("5.0.0").isOlderThan(v("5.0.1"))).isTrue(); assertThat(v("6...
@Bean public ShenyuLoaderService shenyuLoaderService(final ShenyuWebHandler shenyuWebHandler, final PluginDataSubscriber pluginDataSubscriber, final ShenyuConfig config) { return new ShenyuLoaderService(she...
@Test public void testShenyuLoaderService() { applicationContextRunner.run(context -> { ShenyuLoaderService service = context.getBean("shenyuLoaderService", ShenyuLoaderService.class); assertNotNull(service); } ); }
public PrefixList(List<String> prefixList) { if (prefixList == null) { mInnerList = ImmutableList.of(); } else { mInnerList = ImmutableList.copyOf(prefixList); } }
@Test public void prefixList() { PrefixList prefixList = new PrefixList(ImmutableList.of("test", "apple", "sun")); assertTrue(prefixList.inList("test")); assertTrue(prefixList.inList("apple")); assertTrue(prefixList.inList("sun")); assertTrue(prefixList.inList("test123")); assertTrue(prefixLi...
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates) { List<String> perColumnExpressions = new ArrayList<>(); int expressionLength = 0; for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) { String columnName = partition...
@Test public void testSmallintConversion() { Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR) .addIntegerValues("col1", Long.valueOf(Short.MAX_VALUE)) .build(); String expression = buildGlueExpression(predicates); assertEqu...
@VisibleForTesting static Object convertAvroField(Object avroValue, Schema schema) { if (avroValue == null) { return null; } switch (schema.getType()) { case NULL: case INT: case LONG: case DOUBLE: case FLOAT: ...
@Test public void testConvertAvroDouble() { Object converted = BaseJdbcAutoSchemaSink.convertAvroField(Double.MIN_VALUE, createFieldAndGetSchema((builder) -> builder.name("field").type().doubleType().noDefault())); Assert.assertEquals(converted, Double.MIN_VALUE); }
public static void setSelfEnv(Map<String, List<String>> headers) { if (headers != null) { List<String> amoryTagTmp = headers.get(Constants.AMORY_TAG); if (amoryTagTmp == null) { if (selfAmoryTag != null) { selfAmoryTag = null; LOGGE...
@Test void testSetSelfEnv() { Map<String, List<String>> headers = new HashMap<>(); headers.put(Constants.AMORY_TAG, Arrays.asList("a", "1")); headers.put(Constants.VIPSERVER_TAG, Arrays.asList("b", "2")); headers.put(Constants.LOCATION_TAG, Arrays.asList("c", "3")); EnvUtil.s...
@Override public Optional<String> nodeIdToName(String nodeId) { return nodeById(nodeId) .map(jsonNode -> jsonNode.get("name").asText()); }
@Test void returnsNameForNodeId() throws Exception { mockNodesResponse(); assertThat(this.clusterAdapter.nodeIdToName(nodeId)).isNotEmpty() .contains("es02"); }
@POST @ApiOperation("Get all views that match given parameter value") @NoAuditEvent("Only returning matching views, not changing any data") public Collection<ViewParameterSummaryDTO> forParameter(@Context SearchUser searchUser) { return qualifyingViewsService.forValue() .stream() ...
@Test public void returnsAllViewsIfAllArePermitted() { final SearchUser searchUser = TestSearchUser.builder() .allowView("view1") .allowView("view2") .build(); final QualifyingViewsService service = mockViewsService("view1", "view2"); final ...
@Override public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions) { return beginningOffsets(partitions, Duration.ofMillis(defaultApiTimeoutMs)); }
@Test public void testBeginningOffsetsThrowsKafkaExceptionForUnderlyingExecutionFailure() { consumer = newConsumer(); Set<TopicPartition> partitions = mockTopicPartitionOffset().keySet(); Throwable eventProcessingFailure = new KafkaException("Unexpected failure " + "processing Li...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void sendVideoNoteFile() { SendResponse response = bot.execute(new SendVideoNote(chatId, videoNoteFile).thumb(thumbFile).length(20).duration(30)); VideoNoteCheck.check(response.message().videoNote(), true); assertNotEquals("telegram should generate thumb", thumbSize, response.me...
public FEELFnResult<String> invoke(@ParameterName("from") Object val) { if ( val == null ) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) ); } }
@Test void invokeLocalTime() { final LocalTime localTime = LocalTime.now(); FunctionTestUtil.assertResult(stringFunction.invoke(localTime), TimeFunction.FEEL_TIME.format(localTime)); }
@Override protected FederationSearcher doBuild(DeployState deployState, TreeConfigProducer<AnyConfigProducer> ancestor, Element searcherElement) { FederationSearcherModel model = new FederationSearcherModelBuilder(searcherElement).build(); Optional<Component> targetSelector = buildTargetSelector(dep...
@Test void ensureCorrectModel() { FederationSearcher searcher = new DomFederationSearcherBuilder().doBuild(root.getDeployState(), root, parse( "<federation id='theId'>", " <provides>p2</provides>", " <source-set inherits=\"default\" />", ...
@Override @ManagedOperation(description = "Adds the key to the store") public boolean add(String key) { return cache.putIfAbsent(key, true); }
@Test public void addsNewKeysToCache() { assertTrue(repository.add("One")); assertTrue(repository.add("Two")); assertTrue(cache.containsKey("One")); assertTrue(cache.containsKey("Two")); }
@Override public boolean dropTable(TableIdentifier identifier, boolean purge) { if (!isValidIdentifier(identifier)) { return false; } String database = identifier.namespace().level(0); TableOperations ops = newTableOps(identifier); TableMetadata lastMetadata = null; if (purge) { ...
@Test public void testCreateTableDefaultSortOrder() throws Exception { Schema schema = getTestSchema(); PartitionSpec spec = PartitionSpec.builderFor(schema).bucket("data", 16).build(); TableIdentifier tableIdent = TableIdentifier.of(DB_NAME, "tbl"); try { Table table = catalog.createTable(tabl...
@Override public Writable put(K key, Writable value) { addToMap(key.getClass()); addToMap(value.getClass()); return instance.put(key, value); }
@Test @SuppressWarnings("deprecation") public void testForeignClass() { SortedMapWritable<Text> inMap = new SortedMapWritable<Text>(); inMap.put(new Text("key"), new UTF8("value")); inMap.put(new Text("key2"), new UTF8("value2")); SortedMapWritable<Text> outMap = new SortedMapWritable<Text>(inMap); ...
public static void main(String[] args) { // An Executor that provides methods to manage termination and methods that can // produce a Future for tracking progress of one or more asynchronous tasks. ExecutorService executor = null; try { // Create a MessageQueue object. var msgQueue = new ...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { try { final String resourceId = fileid.getFileId(file); final ResourceUpdateModel resourceUpdateModel = new ResourceUpdateModel(); ResourceUpdateModelUpdate resou...
@Test public void testSetTimestampDirectory() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path container = new EueDirectoryFeature(session, fileid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Ty...
public static TopicConsumerConfigurationData ofTopicName(@NonNull String topicName, int priorityLevel) { return of(new TopicNameMatcher.TopicName(topicName), priorityLevel); }
@Test public void testOfFactoryMethod() { TopicConsumerConfigurationData topicConsumerConfigurationData = TopicConsumerConfigurationData .ofTopicName("foo", 1); assertThat(topicConsumerConfigurationData.getTopicNameMatcher().matches("foo")).isTrue(); assertThat(topicConsumer...
public static SQLException toSQLException(final Exception cause, final DatabaseType databaseType) { if (cause instanceof SQLException) { return (SQLException) cause; } if (cause instanceof ShardingSphereSQLException) { return ((ShardingSphereSQLException) cause).toSQLExce...
@Test void assertToSQLExceptionWithShardingSphereSQLException() { ShardingSphereSQLException cause = mock(ShardingSphereSQLException.class); SQLException expected = new SQLException(""); when(cause.toSQLException()).thenReturn(expected); assertThat(SQLExceptionTransformEngine.toSQLEx...
public void publishArtifacts(List<ArtifactPlan> artifactPlans, EnvironmentVariableContext environmentVariableContext) { final File pluggableArtifactFolder = publishPluggableArtifacts(artifactPlans, environmentVariableContext); try { final List<ArtifactPlan> mergedPlans = artifactPlanFilter.g...
@Test public void shouldDeletePluggableArtifactMetadataDirectory() throws Exception { TestFileUtil.createTestFile(workingFolder, "installer.zip"); TestFileUtil.createTestFile(workingFolder, "testreports.xml"); final ArtifactStore artifactStore = new ArtifactStore("s3", "cd.go.s3", create("F...
static Set<PipelineOptionSpec> getOptionSpecs( Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) { Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods); ImmutableSe...
@Test public void testExcludesHiddenInterfaces() { Set<PipelineOptionSpec> properties = PipelineOptionsReflector.getOptionSpecs(HiddenOptions.class, true); assertThat(properties, not(hasItem(hasName("foo")))); }
@Override public CqlSession currentSession() { return cqlSession; }
@Test public void testAsyncQuery(CassandraParams params) { params.execute("create table test_table(id int, value varchar, primary key (id));\n"); params.execute("insert into test_table(id, value) values (1,'test1');\n"); record Entity(Integer id, String value) {} var qctx = new Quer...
@Override public String named() { return PluginEnum.NETTY_HTTP_CLIENT.getName(); }
@Test public void testNamed() { assertEquals(PluginEnum.NETTY_HTTP_CLIENT.getName(), nettyHttpClientPlugin.named()); }
public void ensureFolder(String parentPath, String name) throws IOException, InvalidTokenException { Map<String, Object> rawFolder = new LinkedHashMap<>(); rawFolder.put("name", name); String url; try { url = getUriBuilder() .setPath(API_PATH_PREFIX + "/mounts/primar...
@Test public void testEnsureFolderAlreadyExists() throws Exception { server.enqueue(new MockResponse().setResponseCode(409)); client.ensureFolder("/path/to/folder", "name"); assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); assertEquals("P...
@Override public long computePullFromWhereWithException(MessageQueue mq) throws MQClientException { long result = -1; final ConsumeFromWhere consumeFromWhere = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getConsumeFromWhere(); final OffsetStore offsetStore = this.defaultMQPushC...
@Test public void testComputePullFromWhereWithException_ne_minus1() throws MQClientException { for (ConsumeFromWhere where : new ConsumeFromWhere[]{ ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET, ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET, ConsumeFromWhere.CONSUME_FROM_TIMEST...
@Override public List<Intent> compile(SinglePointToMultiPointIntent intent, List<Intent> installable) { Set<Link> links = new HashSet<>(); final boolean allowMissingPaths = intentAllowsPartialFailure(intent); boolean hasPaths = false; boolean missingS...
@Test public void testNonTrivialSelectorsIntent() { FilteredConnectPoint ingress = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)); Set<FilteredConnectPoint> egress = ImmutableSet.of( new FilteredConnectPoint(new ConnectPoint(DID_3, PORT_1), ...
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testOutlineSetupOnce() { run("outline-setup-once.feature"); }
public Optional<String> findAlias(final String projectionName) { for (Projection each : projections) { if (each instanceof ShorthandProjection) { Optional<Projection> projection = ((ShorthandProjection) each).getActualColumns().stream().filter(optional -> proj...
@Test void assertFindAliasWithOutAlias() { ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.emptyList()); assertFalse(projectionsContext.findAlias("").isPresent()); }
@Override public TenantDO getTenantByWebsite(String website) { return tenantMapper.selectByWebsite(website); }
@Test public void testGetTenantByWebsite() { // mock 数据 TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setWebsite("https://www.iocoder.cn")); tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据 // 调用 TenantDO result = tenantService.getTenantByWebsite("https://www.iocod...
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) { final String storeName = storeQueryParameters.storeName(); final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType(); final List<T> globalStore = globalStoreProvider.stores(storeName, que...
@Test public void shouldReturnKVStoreWithPartitionWhenItExists() { assertNotNull(storeProvider.getStore(StoreQueryParameters.fromNameAndType(keyValueStore, QueryableStoreTypes.keyValueStore()).withPartition(numStateStorePartitions - 1))); }
public long indexOf(double x, double y) { if (!rectangle.contains(x, y)) { // Put things outside the box at the end // This will also handle infinities and NaNs return Long.MAX_VALUE; } int xInt = (int) (xScale * (x - rectangle.getXMin())); int yI...
@Test public void testDegenerateVerticalRectangle() { HilbertIndex hilbert = new HilbertIndex(new Rectangle(0, 0, 0, 4)); assertEquals(hilbert.indexOf(0., 0.), 0); assertTrue(hilbert.indexOf(0., 1.) < hilbert.indexOf(0., 2.)); assertEquals(hilbert.indexOf(2., 0.), Long.MAX_VALUE)...
public T getOrDefault(final T defaultValue) { return _delegate.getOrDefault(defaultValue); }
@Test public void testGetOrDefaultWithValue() { final Promise<String> delegate = Promises.value("value"); final Promise<String> promise = new DelegatingPromise<String>(delegate); assertEquals(delegate.getOrDefault("defaulValue"), promise.getOrDefault("defaultValue")); }
public boolean isValid() throws IOException { if (contractBinary.equals(BIN_NOT_PROVIDED)) { throw new UnsupportedOperationException( "Contract binary not present in contract wrapper, " + "please generate your wrapper using -abiFile=<file>"); }...
@Test public void testIsValidSkipMetadataIpfs() throws Exception { prepareEthGetCode( TEST_CONTRACT_BINARY + "a2646970667358221220" + "a9bc86938894dc250f6ea25dd823d4472fad6087edcda429a3504e3713a9fc880029"); Contract contract = deployCo...
public static void mergeMap(boolean decrypt, Map<String, Object> config) { merge(decrypt, config); }
@Test public void testMap_valueCastToInt() { Map<String, Object> testMap = new HashMap<>(); testMap.put("key", "${TEST.int: 1}"); CentralizedManagement.mergeMap(true, testMap); Assert.assertTrue(testMap.get("key") instanceof Integer); }
@Override public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) { checkForDynamicType(typeDescriptor); return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType()); }
@Test public void testOptionalPrimitiveSchema() { Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(OptionalPrimitive.class)); assertEquals(OPTIONAL_PRIMITIVE_SCHEMA, schema); }
@Override public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { return this.processRequest(ctx.channel(), request, true); }
@Test public void testBatchAck_appendAck() throws RemotingCommandException { { // buffer addAk OK PopBufferMergeService popBufferMergeService = mock(PopBufferMergeService.class); when(popBufferMergeService.addAk(anyInt(), any())).thenReturn(true); when(popMess...
public void subtract(AggregatedMetricValues other) { for (Map.Entry<Short, MetricValues> entry : other.metricValues().entrySet()) { short metricId = entry.getKey(); MetricValues otherValuesForMetric = entry.getValue(); MetricValues valuesForMetric = valuesFor(metricId); if (valuesForMetric =...
@Test public void testDeduct() { Map<Short, MetricValues> valuesByMetricId = getValuesByMetricId(); AggregatedMetricValues aggregatedMetricValues = new AggregatedMetricValues(valuesByMetricId); aggregatedMetricValues.subtract(aggregatedMetricValues); for (Map.Entry<Short, MetricValues> entry : value...
@Override public long getDictDataCountByDictType(String dictType) { return dictDataMapper.selectCountByDictType(dictType); }
@Test public void testGetDictDataCountByDictType() { // mock 数据 dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai"))); dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("tudou"))); dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai"))); //...
public OpenConfigLogicalChannelAssignmentsHandler addAssignment( OpenConfigAssignmentHandler assignment) { modelObject.addToAssignment(assignment.getModelObject()); return this; }
@Test public void testAddAssignment() { // test Handler OpenConfigLogicalChannelAssignmentsHandler logicalChannelAssignments = new OpenConfigLogicalChannelAssignmentsHandler(parent); // call addAssignment OpenConfigAssignmentHandler assignment = new OpenConfigAssignmentH...
public Optional<CloudAccount> cloudAccount() { return cloudAccount; }
@Test public void testCloudAccount() { String json = "{\"cloudAccount\": {\"id\": \"012345678912\"}}"; PrepareParams params = PrepareParams.fromJson(json.getBytes(StandardCharsets.UTF_8), TenantName.defaultName(), Duration.ZERO); assertEquals(CloudAccount.from("012345678912"), params.cloudAc...
public void deregister() { if (StringUtils.isEmpty(RegisterContext.INSTANCE.getClientInfo().getServiceId())) { LOGGER.warning("No service to de-register for nacos client..."); return; } String serviceId = RegisterContext.INSTANCE.getClientInfo().getServiceId(); St...
@Test public void testDeregister() throws NacosException { mockNamingService(); nacosClient.deregister(); Assert.assertNotNull(ReflectUtils.getFieldValue(nacosClient, "instance")); }
@JsonCreator public static SizeBasedRotationStrategyConfig create(@JsonProperty(TYPE_FIELD) String type, @JsonProperty("max_size") @Min(1) long maxSize) { return new AutoValue_SizeBasedRotationStrategyConfig(type, maxSize); }
@Test public void testCreate() throws Exception { final SizeBasedRotationStrategyConfig config = SizeBasedRotationStrategyConfig.create(1000L); assertThat(config.maxSize()).isEqualTo(1000L); }