focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
private void stop(int numOfServicesStarted, boolean stopOnlyStartedServices) { // stop in reverse order of start Exception firstException = null; List<Service> services = getServices(); for (int i = numOfServicesStarted - 1; i >= 0; i--) { Service service = services.get(i); if (LOG.isDebugEn...
@Test(timeout = 10000) public void testAddInitedChildInStart() throws Throwable { CompositeService parent = new CompositeService("parent"); BreakableService child = new BreakableService(); child.init(new Configuration()); parent.init(new Configuration()); parent.start(); AddSiblingService.addC...
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } final Set<String> viewIds = new HashSet<>(); final FindIterable<Document> documents = viewsCollection.find...
@Test @MongoDBFixtures("V20190127111728_MigrateWidgetFormatSettings.json") public void testMigrationWithOneChartColorMapping() { final BasicDBObject dbQuery1 = new BasicDBObject(); dbQuery1.put("_id", new ObjectId("5e2ee372b22d7970576b2eb3")); final MongoCollection<Document> collection =...
boolean shouldReplicateTopic(String topic) { return (topicFilter.shouldReplicateTopic(topic) || replicationPolicy.isHeartbeatsTopic(topic)) && !replicationPolicy.isInternalTopic(topic) && !isCycle(topic); }
@Test public void testReplicatesHeartbeatsByDefault() { MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"), new DefaultReplicationPolicy(), new DefaultTopicFilter(), new DefaultConfigPropertyFilter()); assertTrue(connector.shouldReplicateT...
public static AuditActor system(@Nonnull NodeId nodeId) { return new AutoValue_AuditActor(URN_GRAYLOG_NODE + requireNonNull(nodeId, "nodeId must not be null").getNodeId()); }
@Test(expected = NullPointerException.class) public void testNullSystem() { AuditActor.system(null); }
public static Set<Integer> getProjectedIds(Schema schema) { return ImmutableSet.copyOf(getIdsInternal(schema.asStruct(), true)); }
@Test public void testGetProjectedIds() { Schema schema = new Schema( Lists.newArrayList( required(10, "a", Types.IntegerType.get()), required(11, "A", Types.IntegerType.get()), required(35, "emptyStruct", Types.StructType.of()), ...
public CaseInsensitiveMap() { this(DEFAULT_INITIAL_CAPACITY); }
@Test public void caseInsensitiveMapTest() { CaseInsensitiveMap<String, String> map = new CaseInsensitiveMap<>(); map.put("aAA", "OK"); assertEquals("OK", map.get("aaa")); assertEquals("OK", map.get("AAA")); }
public static Gson instance() { return SingletonHolder.INSTANCE; }
@Test void rejectsSerializationOfDESCipherProvider() { final DESCipherProvider dcp = new DESCipherProvider(new TempSystemEnvironment()); try { final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Serialization.instance().toJson(dcp)); ...
@Subscribe public void onVarbitChanged(VarbitChanged varbitChanged) { if (varbitChanged.getVarbitId() == Varbits.WINTERTODT_TIMER) { int timeToNotify = config.roundNotification(); // Sometimes wt var updates are sent to players even after leaving wt. // So only notify if in wt or after just having left. ...
@Test public void matchStartingNotification_shouldNotNotify_whenNoneOptionSelected() { when(config.roundNotification()).thenReturn(5); VarbitChanged varbitChanged = new VarbitChanged(); varbitChanged.setVarbitId(Varbits.WINTERTODT_TIMER); wintertodtPlugin.onVarbitChanged(varbitChanged); verify(notifier, t...
static WebSocketServerHandshaker getHandshaker(Channel channel) { return channel.attr(HANDSHAKER_ATTR_KEY).get(); }
@Test public void testCheckInvalidWebSocketPath() { HttpRequest httpRequest = new WebSocketRequestBuilder().httpVersion(HTTP_1_1) .method(HttpMethod.GET) .uri("/testabc") .key(HttpHeaderNames.SEC_WEBSOCKET_KEY) .connection("Upgrade") ...
private static Slice decompressZstd(Slice input, int uncompressedSize) { byte[] buffer = new byte[uncompressedSize]; decompress(new ZstdDecompressor(), input, 0, input.length(), buffer, 0); return wrappedBuffer(buffer); }
@Test public void testDecompressZSTD() throws IOException { performTest(ZSTD, 0); performTest(ZSTD, 1); performTest(ZSTD, 100); performTest(ZSTD, 256); performTest(ZSTD, 512); performTest(ZSTD, 1024); }
@Override public byte convertToByte(CharSequence value) { if (value instanceof AsciiString && value.length() == 1) { return ((AsciiString) value).byteAt(0); } return Byte.parseByte(value.toString()); }
@Test public void testByteFromEmptyAsciiString() { assertThrows(NumberFormatException.class, new Executable() { @Override public void execute() { converter.convertToByte(AsciiString.EMPTY_STRING); } }); }
public List<Unstructured> load() { List<Unstructured> unstructuredList = new ArrayList<>(); process((properties, map) -> { Unstructured unstructured = JsonUtils.mapToObject(map, Unstructured.class); unstructuredList.add(unstructured); }); return unstructuredList; ...
@Test void loadTest() { Resource[] resources = yamlResources.toArray(Resource[]::new); YamlUnstructuredLoader yamlUnstructuredLoader = new YamlUnstructuredLoader(resources); List<Unstructured> unstructuredList = yamlUnstructuredLoader.load(); assertThat(unstructuredList).isNotNull();...
@Override public MethodConfig build() { MethodConfig methodConfig = new MethodConfig(); super.build(methodConfig); methodConfig.setArguments(arguments); methodConfig.setDeprecated(deprecated); methodConfig.setExecutes(executes); methodConfig.setName(name); me...
@Test void build() { ArgumentConfig argument = new ArgumentConfig(); MethodBuilder builder = MethodBuilder.newBuilder(); builder.name("name") .stat(1) .retry(true) .reliable(false) .executes(2) .deprecated(true) ...
@Override public Num calculate(BarSeries series, Position position) { return series.one(); }
@Test public void calculateWithTwoPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series), Trade.buyAt(3, series), Trade.sellAt(5, series)); ...
public Filter parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) { if (!filterExpression.contains(FIELD_AND_VALUE_SEPARATOR)) { throw new IllegalArgumentException(WRONG_FILTER_EXPR_FORMAT_ERROR_MSG); } final String[] split = filterExpression....
@Test void parsesFilterExpressionCorrectlyForStringType() { assertEquals(new SingleValueFilter("owner", "baldwin"), toTest.parseSingleExpression("owner:baldwin", List.of(EntityAttribute.builder() .id("owner") ...
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaul...
@Test public void testExecute() throws SubCommandException { ConsumerConnectionSubCommand cmd = new ConsumerConnectionSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-g default-consumer-group", "-b localhost:" + brokerMocke...
@Override public SnowflakeTableMetadata loadTableMetadata(SnowflakeIdentifier tableIdentifier) { Preconditions.checkArgument( tableIdentifier.type() == SnowflakeIdentifier.Type.TABLE, "loadTableMetadata requires a TABLE identifier, got '%s'", tableIdentifier); SnowflakeTableMetadata ta...
@SuppressWarnings("unchecked") @Test public void testGetS3TableMetadata() throws SQLException { when(mockResultSet.next()).thenReturn(true); when(mockResultSet.getString("METADATA")) .thenReturn( "{\"metadataLocation\":\"s3://tab1/metadata/v3.metadata.json\",\"status\":\"success\"}"); ...
@Override public PageResult<AdminUserDO> getUserPage(UserPageReqVO reqVO) { return userMapper.selectPage(reqVO, getDeptCondition(reqVO.getDeptId())); }
@Test public void testGetUserPage() { // mock 数据 AdminUserDO dbUser = initGetUserPageData(); // 准备参数 UserPageReqVO reqVO = new UserPageReqVO(); reqVO.setUsername("tu"); reqVO.setMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqV...
public void fillMaxSpeed(Graph graph, EncodingManager em) { // In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info, // but now we have and can fill the country-dependent max_speed value where missing. EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(...
@Test public void testRoundabout() { ReaderWay way = new ReaderWay(0L); way.setTag("country", Country.CRI); way.setTag("highway", "primary"); EdgeIteratorState edge = createEdge(way).set(urbanDensity, CITY); calc.fillMaxSpeed(graph, em); assertEquals(50, edge.get(maxS...
@Override public AuthorizationPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { Capabilities capabilities = capabilities(descriptor.id()); PluggableInstanceSettings authConfigSettings = authConfigSettings(descriptor.id()); PluggableInstanceSettings roleSettings = roleSettings(descri...
@Test public void shouldNotHaveRoleSettingsInPluginInfoIfPluginCannotAuthorize() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); Capabilities capabilities = new Capabilities(SupportedAuthType.Password, true, false, false); when(extension.getCapabilities...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { final boolean exists = Files.exists(session.toPath(file), LinkOption.NOFOLLOW_LINKS); if(exists) { if(Files.isSymbolicLink(session.toPath(file))) { return true...
@Test public void testFindNotFound() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallba...
public static String toHexString(byte[] src) { return toHexString(src, 0, src.length); }
@Test public void testToHexString() { assertThat(toHexString(new byte[] { 0 }), is("0")); assertThat(toHexString(new byte[] { 1 }), is("1")); assertThat(toHexString(new byte[] { 0, 0 }), is("0")); assertThat(toHexString(new byte[] { 1, 0 }), is("100")); assertThat(toHexString...
public Connector createConnector(Props props) { Connector connector = new Connector(HTTP_PROTOCOL); connector.setURIEncoding("UTF-8"); connector.setProperty("address", props.value(WEB_HOST.getKey(), "0.0.0.0")); connector.setProperty("socket.soReuseAddress", "true"); // See Tomcat configuration refe...
@Test public void createConnector_shouldUseHardcodedPropertiesWhereNeeded() { Props props = getEmptyProps(); Connector connector = tomcatHttpConnectorFactory.createConnector(props); // General properties assertThat(connector.getURIEncoding()).isEqualTo("UTF-8"); assertThat(connector.getProperty("...
@Override public void execute( RunConfiguration runConfiguration, ExecutionConfiguration executionConfiguration, AbstractMeta meta, VariableSpace variableSpace, Repository repository ) throws KettleException { DefaultRunConfiguration defaultRunConfiguration = (DefaultRunConfiguration) runCo...
@Test public void testExecutePentahoJob() throws Exception { DefaultRunConfiguration defaultRunConfiguration = new DefaultRunConfiguration(); defaultRunConfiguration.setName( "Default Configuration" ); defaultRunConfiguration.setLocal( false ); defaultRunConfiguration.setPentaho( true ); defaultRu...
@Override public <U> ParSeqBasedCompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) { Task<U> that = getOrGenerateTaskFromStage(other); return nextStageByComposingTask( Task.par(_task, that).flatMap("thenAcceptBoth", (t, u) -> Task....
@Test public void testThenAcceptBoth() throws Exception { CompletionStage<String> completionStage1 = createTestStage(TESTVALUE1); CompletionStage<String> completionStage2 = createTestStage(TESTVALUE2); BiConsumer<String, String> consumer = mock(BiConsumer.class); finish(completionStage1.thenAcceptBoth(...
public void execute() { if (indexesAreEnabled()) { stream(indexers) .forEach(this::indexUninitializedTypes); } }
@Test public void index_if_not_initialized() { doReturn(false).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(indexer).getIndexTypes(); verify(indexer).indexOnStartup(Mockito.eq(ImmutableSet.of(TYPE_FAKE))); }
public void remove(K key) { checkState( !isClosed, "Multimap user state is no longer usable because it is closed for %s", keysStateRequest.getStateKey()); Object keyStructuralValue = mapKeyCoder.structuralValue(key); pendingAdds.remove(keyStructuralValue); if (!isCleared) { ...
@Test public void testRemove() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient( ImmutableMap.of( createMultimapKeyStateKey(), KV.of(ByteArrayCoder.of(), singletonList(A1)), createMultimapValueStateKey(A1), ...
@VisibleForTesting Integer convertSmsTemplateAuditStatus(int templateStatus) { switch (templateStatus) { case 1: return SmsTemplateAuditStatusEnum.CHECKING.getStatus(); case 0: return SmsTemplateAuditStatusEnum.SUCCESS.getStatus(); case -1: return SmsTemplateAuditStatusEn...
@Test public void testConvertSmsTemplateAuditStatus() { assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(), smsClient.convertSmsTemplateAuditStatus(0)); assertEquals(SmsTemplateAuditStatusEnum.CHECKING.getStatus(), smsClient.convertSmsTemplateAuditStatus(1));...
public static NodeBadge glyph(String gid) { return new NodeBadge(Status.INFO, true, nonNull(gid), null); }
@Test public void glyphWarn() { badge = NodeBadge.glyph(Status.WARN, GID); checkFields(badge, Status.WARN, true, GID, null); }
@Override public int run(String[] args) throws Exception { try { webServiceClient = WebServiceClient.getWebServiceClient().createClient(); return runCommand(args); } finally { if (yarnClient != null) { yarnClient.close(); } if (webServiceClient != null) { webServi...
@Test (timeout = 15000) public void testFetchFinishedApplictionLogs() throws Exception { String remoteLogRootDir = "target/logs/"; conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); conf .set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogRootDir); conf.setBoolean(YarnConfigura...
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 poolReSubscribesAndReadsRecordsAfterCheckPoint() throws Exception { kinesis = new EFOStubbedKinesisAsyncClient(10); kinesis.stubSubscribeToShard("shard-000", eventWithRecords(3)); kinesis.stubSubscribeToShard("shard-001", eventWithRecords(11, 3)); KinesisReaderCheckpoint initialChec...
public BackgroundJobServerConfiguration andServerTimeoutPollIntervalMultiplicand(int multiplicand) { if (multiplicand < 4) throw new IllegalArgumentException("The smallest possible ServerTimeoutPollIntervalMultiplicand is 4 (4 is also the default)"); this.serverTimeoutPollIntervalMultiplicand = multipli...
@Test void isServerTimeoutMultiplicandIsSmallerThan4AnExceptionIsThrown() { assertThatThrownBy(() -> backgroundJobServerConfiguration.andServerTimeoutPollIntervalMultiplicand(3)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The smallest possible ServerTimeoutPol...
public <T> T convert(String property, Class<T> targetClass) { final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass); if (converter == null) { throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalNa...
@Test void testConvertBooleanIllegal() { assertThrows(IllegalArgumentException.class, () -> { compositeConverter.convert("aaa", Boolean.class); }); }
public static String rangeKey(long value) { return encodeBase62(value, true); }
@Test public void testRangeKey() { Assert.assertEquals("44C92", IdHelper.rangeKey(1000000L)); Assert.assertEquals("71l9Zo9o", IdHelper.rangeKey(100000000000L)); Assert.assertTrue(IdHelper.rangeKey(1000000L).compareTo(IdHelper.rangeKey(100000000000L)) < 0); }
@Override public MaskRuleConfiguration findRuleConfiguration(final ShardingSphereDatabase database) { return database.getRuleMetaData().findSingleRule(MaskRule.class) .map(optional -> getConfiguration(optional.getConfiguration())).orElseGet(() -> new MaskRuleConfiguration(new LinkedList<>(),...
@Test void assertFindRuleConfigurationWhenRuleDoesNotExist() { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getRuleMetaData().findSingleRule(MaskRule.class)).thenReturn(Optional.empty()); assertTrue(new MaskAlgorithmChangedProcessor(...
public static Set<String> findKeywordsFromCrashReport(String crashReport) { Matcher matcher = CRASH_REPORT_STACK_TRACE_PATTERN.matcher(crashReport); Set<String> result = new HashSet<>(); if (matcher.find()) { for (String line : matcher.group("stacktrace").split("\\n")) { ...
@Test public void mapletree() throws IOException { assertEquals( new HashSet<>(Arrays.asList("MapleTree", "bamboo", "uraniummc", "ecru")), CrashReportAnalyzer.findKeywordsFromCrashReport(loadLog("/crash-report/mod/mapletree.txt"))); }
@Override public void onChange(List<JobRunrMetadata> metadataList) { if (this.serversWithPollIntervalInSecondsTimeBoxTooSmallMetadataList == null || this.serversWithPollIntervalInSecondsTimeBoxTooSmallMetadataList.size() != metadataList.size()) { problems.removeProblemsOfType(PollIntervalInSecon...
@Test void ifPollIntervalInSecondsTimeBoxIsTooSmallIsDeletedThenProblemIsRemoved() { final JobRunrMetadata jobRunrMetadata = new JobRunrMetadata(PollIntervalInSecondsTimeBoxIsTooSmallNotification.class.getSimpleName(), "BackgroundJobServer " + UUID.randomUUID(), "23"); pollIntervalInSecondsTimeBoxIs...
Record deserialize(Object data) { return (Record) fieldDeserializer.value(data); }
@Test public void testDeserializeEverySupportedType() { assumeThat(HiveVersion.min(HiveVersion.HIVE_3)) .as("No test yet for Hive3 (Date/Timestamp creation)") .isFalse(); Deserializer deserializer = new Deserializer.Builder() .schema(HiveIcebergTestUtils.FULL_SCHEMA) ...
public ParseTree getRootNode() { return parseTree.getChild(0); }
@Test void assertGetRootNode() { ParseTree parseTree = mock(ParseTree.class); when(parseTree.getChild(0)).thenReturn(parseTree); assertThat(new ParseASTNode(parseTree, mock(CommonTokenStream.class)).getRootNode(), is(parseTree)); }
public void add(long member) { assert member >= 0; int prefix = (int) (member >>> Integer.SIZE); if (prefix == lastPrefix) { Storage32 newStorage = lastStorage.add((int) member); if (newStorage != lastStorage) { // storage was upgraded las...
@Test public void testAdd() { // try empty set verify(); // at the beginning for (long i = 0; i < ARRAY_STORAGE_32_MAX_SIZE / 2; ++i) { set(i); verify(); set(i); verify(); } // offset for (long i = 1000000; i <...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertDecimal() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("DECIMAL") .dataType("DECIMAL") .build(); Column column = ...
public static NetworkPolicyPeer createPeer(Map<String, String> podSelector, LabelSelector namespaceSelector) { return new NetworkPolicyPeerBuilder() .withNewPodSelector() .withMatchLabels(podSelector) .endPodSelector() .withNamespaceSelector(na...
@Test public void testCreatePeerWithPodLabels() { NetworkPolicyPeer peer = NetworkPolicyUtils.createPeer(Map.of("labelKey", "labelValue")); assertThat(peer.getNamespaceSelector(), is(nullValue())); assertThat(peer.getPodSelector().getMatchLabels(), is(Map.of("labelKey", "labelValue"))); ...
public static String decodeMessage(String raw) { if (StringUtils.isEmpty(raw)) { return ""; } return QueryStringDecoder.decodeComponent(raw); }
@Test void decodeMessage() { String message = "😯"; Assertions.assertEquals(message, TriRpcStatus.decodeMessage(TriRpcStatus.encodeMessage(message))); Assertions.assertTrue(TriRpcStatus.decodeMessage("").isEmpty()); Assertions.assertTrue(TriRpcStatus.decodeMessage(null).isEmpty()); ...
@Override public void executeSystemTask(WorkflowSystemTask systemTask, String taskId, int callbackTime) { try { Task task = executionDAOFacade.getTaskById(taskId); if (task == null) { LOG.error("TaskId: {} could not be found while executing SystemTask", taskId); return; } L...
@Test public void testExecuteSystemTaskThrowExceptionDuringConfigureCallbackInterval() { String workflowId = "workflow-id"; String taskId = "task-id-1"; Task maestroTask = new Task(); maestroTask.setTaskType(Constants.MAESTRO_TASK_NAME); maestroTask.setReferenceTaskName("maestroTask"); maestr...
public static Date toDate(Object value, Date defaultValue) { return convertQuietly(Date.class, value, defaultValue); }
@Test public void toDateTest() { assertThrows(DateException.class, () -> { // 默认转换失败报错而不是返回null Convert.convert(Date.class, "aaaa"); }); }
public static String jaasConfig(String moduleName, Map<String, String> options) { StringJoiner joiner = new StringJoiner(" "); for (Entry<String, String> entry : options.entrySet()) { String key = Objects.requireNonNull(entry.getKey()); String value = Objects.requireNonNull(entry...
@Test public void testValueContainsEqualSign() { Map<String, String> options = new HashMap<>(); options.put("key1", "value=1"); String moduleName = "Module"; String expected = "Module required key1=\"value=1\";"; assertEquals(expected, AuthenticationUtils.jaasConfig(moduleNa...
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"}) public static boolean isScalablePushQuery( final Statement statement, final KsqlExecutionContext ksqlEngine, final KsqlConfig ksqlConfig, final Map<String, Object> overrides ) { if (!isPushV2Enabled(ksqlConfig, ov...
@Test public void shouldNotMakeQueryWithRowpartitionInSelectClauseScalablePush() { try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) { // Given: expectIsSPQ(SystemColumns.ROWPARTITION_NAME, columnExtractor); // When: final boolean isScalablePush = Scal...
public static List<String> normalizeColumns(List<Object> columns) { return columns.stream() .map(TableDataUtils::normalizeColumn) .collect(Collectors.toList()); }
@Test void testColumns() { assertEquals(Arrays.asList("hello world", "hello world"), TableDataUtils.normalizeColumns(new Object[]{"hello\tworld", "hello\nworld"})); assertEquals(Arrays.asList("hello world", "null"), TableDataUtils.normalizeColumns(new String[]{"hello\tworld", null}));...
@Override public byte[] serialize(MySqlSplit split) throws IOException { if (split.isSnapshotSplit()) { final MySqlSnapshotSplit snapshotSplit = split.asSnapshotSplit(); // optimization: the splits lazily cache their own serialized form if (snapshotSplit.serializedFormCac...
@Test public void testRepeatedSerializationCache() throws Exception { final MySqlSplit split = new MySqlSnapshotSplit( TableId.parse("test_db.test_table"), "test_db.test_table-0", new RowType( ...
@VisibleForTesting static boolean isReaperThreadRunning() { synchronized (REAPER_THREAD_LOCK) { return null != REAPER_THREAD && REAPER_THREAD.isAlive(); } }
@Test void testReaperThreadSpawnAndStop() throws Exception { assertThat(SafetyNetCloseableRegistry.isReaperThreadRunning()).isFalse(); try (SafetyNetCloseableRegistry ignored = new SafetyNetCloseableRegistry()) { assertThat(SafetyNetCloseableRegistry.isReaperThreadRunning()).isTrue(); ...
public static NormalKey createFromSpec(String spec) { if (spec == null || !spec.contains(":")) { throw new IllegalArgumentException("Invalid spec format"); } String[] parts = spec.split(":", 2); if (parts.length != 2) { throw new IllegalArgumentException("Invalid...
@Test public void testCreateFromSpec_InvalidSpecFormat() { assertThrows(IllegalArgumentException.class, () -> { NormalKey.createFromSpec("invalid_spec_format"); }); }
public abstract boolean passes(T object);
@Test public void testPasses() { String keep = "keep"; String fail = "fail"; assertTrue("String contained keep - but passes returned false.", TEST_FILTER.passes(keep)); assertFalse("String contained fail - but passes returned true.", TEST_FILTER.passes(fail)); }
public static SchemaAndValue parseString(String value) { if (value == null) { return NULL_SCHEMA_AND_VALUE; } if (value.isEmpty()) { return new SchemaAndValue(Schema.STRING_SCHEMA, value); } ValueParser parser = new ValueParser(new Parser(value)); ...
@Test public void shouldParseArrayContainingMap() { SchemaAndValue schemaAndValue = Values.parseString("[{}]"); assertEquals(Type.ARRAY, schemaAndValue.schema().type()); assertEquals(Type.MAP, schemaAndValue.schema().valueSchema().type()); }
public synchronized <K, V> KStream<K, V> stream(final String topic) { return stream(Collections.singleton(topic)); }
@Test public void shouldAllowStreamsFromSameTopic() { builder.stream("topic"); builder.stream("topic"); assertBuildDoesNotThrow(builder); }
@Override public Collection<V> values() { return wrapperMap.values(); }
@Test public void testValues() { CharSequenceMap<String> map = CharSequenceMap.create(); map.put("key1", "value1"); map.put("key2", "value2"); assertThat(map.values()).containsAll(ImmutableList.of("value1", "value2")); }
public static Integer parseRestBindPortFromWebInterfaceUrl(String webInterfaceUrl) { if (webInterfaceUrl != null) { final int lastColon = webInterfaceUrl.lastIndexOf(':'); if (lastColon == -1) { return -1; } else { try { re...
@Test void testParseRestBindPortFromWebInterfaceUrlWithInvalidPort() { assertThat(ResourceManagerUtils.parseRestBindPortFromWebInterfaceUrl("localhost:port1")) .isEqualTo(-1); }
@GetMapping("") @RequiresPermissions("system:manager:list") public ShenyuAdminResult queryDashboardUsers(final String userName, @RequestParam @NotNull(message = "currentPage not null") final Integer currentPage, @R...
@Test public void queryDashboardUsers() throws Exception { final CommonPager<DashboardUserVO> commonPager = new CommonPager<>(new PageParameter(), Collections.singletonList(dashboardUserVO)); given(dashboardUserService.listByPage(any())).willReturn(commonPager); final String ...
public DirectoryEntry lookUp( File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); DirectoryEntry result = lookUp(workingDirectory, path, options, 0); if (result == null) { // an intermediate file in the path...
@Test public void testLookup_absolute_finalSymlink() throws IOException { assertExists(lookup("/work/four/five"), "/", "foo"); assertExists(lookup("/work/four/six"), "work", "one"); }
@Override public T addTimeMillis(K name, long value) { throw new UnsupportedOperationException("read only"); }
@Test public void testAddTimeMillis() { assertThrows(UnsupportedOperationException.class, new Executable() { @Override public void execute() { HEADERS.addTimeMillis("name", 0); } }); }
public int size() { return sha1.digest().length; }
@Test public void testSize() { byte[] buf = new byte[1024]; Arrays.fill(buf, (byte) 0xAA); ZDigest digest = new ZDigest(); digest.update(buf); int size = digest.size(); assertThat(size, is(20)); }
@Override public String convertDestination(ProtocolConverter converter, Destination d) { if (d == null) { return null; } ActiveMQDestination activeMQDestination = (ActiveMQDestination)d; String physicalName = activeMQDestination.getPhysicalName(); String rc = con...
@Test(timeout = 10000) public void testConvertQueue() throws Exception { ActiveMQDestination destination = translator.convertDestination(converter, "/queue/test", false); assertFalse(destination.isComposite()); assertEquals("test", destination.getPhysicalName()); assertEquals(Active...
public static IOException maybeExtractIOException( String path, Throwable thrown, String message) { if (thrown == null) { return null; } // walk down the chain of exceptions to find the innermost. Throwable cause = getInnermostThrowable(thrown.getCause(), thrown); // see i...
@Test public void testNoRouteToHostExceptionExtraction() throws Throwable { intercept(NoRouteToHostException.class, "top", () -> { throw maybeExtractIOException("p2", sdkException("top", sdkException("middle", new NoRouteToHostException("bott...
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 invokeBigDecimal() { FunctionTestUtil.assertResult(stringFunction.invoke(BigDecimal.valueOf(10.7)), "10.7"); }
@Override public void debug(String msg) { logger.debug(msg); }
@Test void testMarkerDebugWithFormat() { jobRunrDashboardLogger.debug(marker, "Debug with {}", "format"); verify(slfLogger).debug(marker, "Debug with {}", "format"); }
@Override public SearchResult<String> searchWorkflows( String workflowName, String status, int start, int count, List<String> options) { return withMetricLogError( () -> getSearchIds( GET_WORKFLOW_INSTANCE_IDS_STATEMENT_TEMPLATE, workflowName, ...
@Test public void searchWorkflowsTest() { SearchResult<String> result = dao.searchWorkflows(TEST_WORKFLOW_NAME, "RUNNING", 0, 10, null); assertEquals(1, result.getTotalHits()); assertEquals(TEST_WORKFLOW_ID, result.getResults().get(0)); result = dao.searchWorkflows(TEST_WORKFLOW_ID, "RUNNING", 1, 10, ...
public static boolean isCaseSensitiveCustomerId(final String customerId) { return NEW_CUSTOMER_CASE_SENSISTIVE_PATTERN.matcher(customerId).matches(); }
@Test public void testCaseInsensitiveNewCustomerIds() { for (String validValue : CustomerIdExamples.VALID_CASE_INSENSISTIVE_NEW_CUSTOMER_IDS) { assertFalse(validValue + " is case-sensitive customer ID.", BaseSupportConfig.isCaseSensitiveCustomerId(validValue)); } }
public void commit() throws IOException { if (completed) return; completed = true; // move this object out of the scope first before save, or otherwise the save() method will do nothing. pop(); saveable.save(); }
@Test public void nestedBulkChange() throws Exception { Point pt = new Point(); Point pt2 = new Point(); BulkChange bc1 = new BulkChange(pt); try { BulkChange bc2 = new BulkChange(pt2); try { BulkChange bc3 = new BulkChange(pt); ...
public void mergeExistingOpenIssue(DefaultIssue raw, DefaultIssue base) { Preconditions.checkArgument(raw.isFromExternalRuleEngine() != (raw.type() == null), "At this stage issue type should be set for and only for external issues"); Rule rule = ruleRepository.getByKey(raw.ruleKey()); raw.setKey(base.key())...
@Test public void mergeExistingOpenIssue() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setRuleKey(XOO_X1) .setRuleDescriptionContextKey("spring") .setCleanCodeAttribute(CleanCodeAttribute.IDENTIFIABLE) .setCodeVariants(Set.of("foo", "bar")) ....
@Override public CompletionStage<Void> setAsync(K key, V value) { return cache.putAsync(key, value); }
@Test public void testSetAsync() throws Exception { cache.put(42, "oldValue"); Future<Void> future = adapter.setAsync(42, "newValue").toCompletableFuture(); Void oldValue = future.get(); assertNull(oldValue); assertEquals("newValue", cache.get(42)); }
static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) { while (messageCount < maxMessages || maxMessages == -1) { ConsumerRecord<byte[], byte[]> msg; try { msg = consumer.receive(); ...
@Test public void shouldResetUnConsumedOffsetsBeforeExit() throws IOException { String topic = "test"; int maxMessages = 123; int totalMessages = 700; long startOffset = 0L; MockConsumer<byte[], byte[]> mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); ...
@Override public ChannelFuture writeRstStream( ChannelHandlerContext ctx, int streamId, long errorCode, ChannelPromise promise) { ChannelPromise newPromise = handleOutstandingControlFrames(ctx, promise); if (newPromise == null) { return promise; } return super...
@Test public void testLimitRst() { assertFalse(encoder.writeRstStream(ctx, 1, CANCEL.code(), newPromise()).isDone()); // The second write is always marked as success by our mock, which means it will also not be queued and so // not count to the number of queued frames. assertTrue(enc...
@Override public void shutdown(long awaitTerminateMillis) { this.stopped = true; this.scheduledExecutorService.shutdown(); ThreadUtils.shutdownGracefully(this.consumeExecutor, awaitTerminateMillis, TimeUnit.MILLISECONDS); if (MessageModel.CLUSTERING.equals(this.defaultMQPushConsumerI...
@Test public void testShutdown() throws IllegalAccessException { popService.shutdown(3000L); Field scheduledExecutorServiceField = FieldUtils.getDeclaredField(popService.getClass(), "scheduledExecutorService", true); Field consumeExecutorField = FieldUtils.getDeclaredField(popService.getClas...
public synchronized void insertJobEntryDatabase( ObjectId id_job, ObjectId id_jobentry, ObjectId id_database ) throws KettleException { // First check if the relationship is already there. // There is no need to store it twice! RowMetaAndData check = getJobEntryDatabase( id_jobentry ); if ( check.getIn...
@Test public void testInsertJobEntryDatabase() throws KettleException { doReturn( getNullIntegerRow() ).when( repo.connectionDelegate ).getOneRow( anyString(), anyString(), any( ObjectId.class ) ); ArgumentCaptor<String> argumentTableName = ArgumentCaptor.forClass( String.class ); ArgumentCaptor<Row...
public static String[] parseUri(String uri) { return doParseUri(uri, false); }
@Test public void testParseEmptyQuery() { String[] out1 = CamelURIParser.parseUri("file:relative"); assertEquals("file", out1[0]); assertEquals("relative", out1[1]); assertNull(out1[2]); String[] out2 = CamelURIParser.parseUri("file:relative?"); assertEquals("file", ...
@Override public PageResult<TenantDO> getTenantPage(TenantPageReqVO pageReqVO) { return tenantMapper.selectPage(pageReqVO); }
@Test public void testGetTenantPage() { // mock 数据 TenantDO dbTenant = randomPojo(TenantDO.class, o -> { // 等会查询到 o.setName("芋道源码"); o.setContactName("芋艿"); o.setContactMobile("15601691300"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); ...
public void removeTemplateNamed(CaseInsensitiveString name) { PipelineTemplateConfig toBeRemoved = null; for (PipelineTemplateConfig templateConfig : this) { if (templateConfig.matches(name)) { toBeRemoved = templateConfig; } } this.remove(toBeRemo...
@Test public void shouldIgnoreTryingToRemoveNonExistentTemplate() { TemplatesConfig templates = new TemplatesConfig(template("template1"), template("template2")); templates.removeTemplateNamed(new CaseInsensitiveString("sachin")); assertThat(templates.size(), is(2)); }
@Override public void deleteDataSourceConfig(Long id) { // 校验存在 validateDataSourceConfigExists(id); // 删除 dataSourceConfigMapper.deleteById(id); }
@Test public void testDeleteDataSourceConfig_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> dataSourceConfigService.deleteDataSourceConfig(id), DATA_SOURCE_CONFIG_NOT_EXISTS); }
@Override public ServerLoaderInfoResponse handle(ServerLoaderInfoRequest request, RequestMeta meta) throws NacosException { ServerLoaderInfoResponse serverLoaderInfoResponse = new ServerLoaderInfoResponse(); serverLoaderInfoResponse.putMetricsValue("conCount", String.valueOf(connectionManager.curren...
@Test void testHandle() { Mockito.when(connectionManager.currentClientsCount()).thenReturn(1); Mockito.when(connectionManager.currentClientsCount(Mockito.any())).thenReturn(1); ServerLoaderInfoRequest request = new ServerLoaderInfoRequest(); RequestMeta meta = new RequestMet...
@Override public boolean hasFooter() { switch (super.getVersion()) { case DEFAULT_VERSION: return false; case 1: return true; default: return false; } }
@Test public void testHasFooter() { assertFalse(verDefault.hasFooter()); assertTrue(verCurrent.hasFooter()); HoodieLogFormatVersion verNew = new HoodieLogFormatVersion(HoodieLogFormat.CURRENT_VERSION + 1); assertFalse(verNew.hasFooter()); }
@Override public void fulfillFinishedTaskStatus(Map<OperatorID, OperatorState> operatorStates) { if (!mayHaveFinishedTasks) { return; } Map<JobVertexID, ExecutionJobVertex> partlyFinishedVertex = new HashMap<>(); for (Execution task : finishedTasks) { JobVert...
@Test void testFulfillFullyFinishedStatesWithCoordinator() throws Exception { JobVertexID finishedJobVertexID = new JobVertexID(); OperatorID finishedOperatorID = new OperatorID(); ExecutionGraph executionGraph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraph...
public void registerUrl( String urlString ) { if ( urlString == null || addedAllClusters == true ) { return; //We got no url or already added all clusters so nothing to do. } if ( urlString.startsWith( VARIABLE_START ) ) { addAllClusters(); } Pattern r = Pattern.compile( URL_PATTERN ); ...
@Test public void testRegisterUrlNotNc() throws Exception { namedClusterEmbedManager.registerUrl( "hdfs://" + CLUSTER1_NAME + "/dir1/dir2" ); verify( mockMetaStoreFactory, never() ).saveElement( any() ); }
public static List<String> buildList(Object propertyValue, String listSeparator) { List<String> valueList = new ArrayList<>(); if (propertyValue != null) { if (propertyValue instanceof List<?>) { @SuppressWarnings("unchecked") List<String> list = (List<String>)propertyValue; ...
@Test public void testStringObject() { List<String> actualList = ConfigValueExtractor.buildList("foo, bar, baz", ","); List<String> expectedList = Arrays.asList(new String[]{"foo", "bar", "baz"}); Assert.assertEquals(expectedList, actualList); }
public static List<SourceToTargetMapping> getCurrentMappings( List<String> sourceFields, List<String> targetFields, List<MappingValueRename> mappingValues ) { List<SourceToTargetMapping> sourceToTargetMapping = new ArrayList<>( ); if ( sourceFields == null || targetFields == null || mappingValues == null ) { ...
@Test public void getCurrentMapping() { List<SourceToTargetMapping> currentMapping = MappingUtil.getCurrentMappings( sourceFields, targetFields, mappingValues ); assertEquals( 2, currentMapping.size() ); assertEquals( currentMapping.get( 0 ).getSourcePosition(), sourceFields.indexOf( "source1" ) ); a...
public static boolean isAwsHostname(final String hostname) { return isAwsHostname(hostname, true); }
@Test public void testAwsHostnames() { assertFalse(S3Session.isAwsHostname("play.min.io")); assertTrue(S3Session.isAwsHostname("test-eu-west-3-cyberduck.s3.amazonaws.com")); assertTrue(S3Session.isAwsHostname("s3.dualstack.eu-west-3.amazonaws.com")); assertTrue(S3Session.isAwsHostnam...
@Override public void unlock() { unlockInner(locks); }
@Test public void testLockSuccess2() throws IOException, InterruptedException { RedisProcess redis1 = redisTestMultilockInstance(); RedisProcess redis2 = redisTestMultilockInstance(); RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort()); RedissonClient client...
public ElasticAgentInformationDTO getElasticAgentInformationDTO(ElasticAgentInformation elasticAgentInformation) { return elasticAgentInformationConverterV5.toDTO(elasticAgentInformation); }
@Test public void shouldGetRequestBodyForMigrateCall_withNewConfig() throws CryptoException { ConfigurationProperty property1 = new ConfigurationProperty(new ConfigurationKey("key"), new ConfigurationValue("value")); ConfigurationProperty property2 = new ConfigurationProperty(new ConfigurationKey("k...
public String getQueueName(final Exchange exchange) { return getOption(QueueExchangeHeaders::getQueueNameFromHeaders, configuration::getQueueName, exchange); }
@Test public void testIfCorrectOptionsReturnedCorrectly() { final QueueConfiguration configuration = new QueueConfiguration(); // first case: when exchange is set final Exchange exchange = new DefaultExchange(context); final QueueConfigurationOptionsProxy configurationOptionsProxy =...
public static <T> T[] checkNonEmpty(T[] array, String name) { //No String concatenation for check if (checkNotNull(array, name).length == 0) { throw new IllegalArgumentException("Param '" + name + "' must not be empty"); } return array; }
@Test public void testCheckNonEmptyTString() { Exception actualEx = null; try { ObjectUtil.checkNonEmpty((Object[]) NULL_OBJECT, NULL_NAME); } catch (Exception e) { actualEx = e; } assertNotNull(actualEx, TEST_RESULT_NULLEX_OK); assertTrue(actu...
public static Set<X509Certificate> filterValid( X509Certificate... certificates ) { final Set<X509Certificate> results = new HashSet<>(); if (certificates != null) { for ( X509Certificate certificate : certificates ) { if ( certificate == null ) ...
@Test public void testFilterValidWithMixOfValidityAndDuplicates() throws Exception { // Setup fixture. final X509Certificate validA = KeystoreTestUtils.generateValidCertificate().getCertificate(); final X509Certificate validB = KeystoreTestUtils.generateValidCertificate().getCertificate(...
public void isAbsent() { if (actual == null) { failWithActual(simpleFact("expected absent optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be absent"), fact("but was present with value", actual.get())); } }
@Test public void isAbsent() { assertThat(Optional.absent()).isAbsent(); }
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testMissedDoubleMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); Message msg = getSampleMessage(); msg.addField("something", "12.4"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); }
public static boolean matches(MetricsFilter filter, MetricKey key) { if (filter == null) { return true; } @Nullable String stepName = key.stepName(); if (stepName == null) { if (!filter.steps().isEmpty()) { // The filter specifies steps, but the metric is not associated with a step....
@Test public void testMatchCompositeStepNameFilters() { // MetricsFilter with a Class-namespace + name filter + step filter. // Successful match. assertTrue( MetricFiltering.matches( MetricsFilter.builder() .addNameFilter(MetricNameFilter.named(MetricFilteringTest.class...
public void onStatsPersistMsg(StatsPersistMsg msg) { if (msg.isEmpty()) { return; } systemContext.getEventService().saveAsync(StatisticsEvent.builder() .tenantId(msg.getTenantId()) .entityId(msg.getEntityId().getId()) .serviceId(systemC...
@Test void givenNonEmptyStatMessage_whenOnStatsPersistMsg_thenNoAction() { statsActor.onStatsPersistMsg(new StatsPersistMsg(0, 1, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)); verify(eventService, times(1)).saveAsync(any(Event.class)); statsActor.onStatsPersistMsg(new StatsPersistMsg(1, ...
public RequestHandler getByRequestType(String requestType) { return registryHandlers.get(requestType); }
@Test void testGetByRequestType() { assertNotNull(registry.getByRequestType(HealthCheckRequest.class.getSimpleName())); }
public boolean consume(TokenQueue tokenQueue, List<Statement> statements) { Token nextToken = tokenQueue.peek(); while (nextToken != null) { boolean channelConsumed = false; for (StatementChannel channel : channels) { if (channel.consume(tokenQueue, statements)) { channelConsumed =...
@Test public void shouldConsume() { TokenMatcher tokenMatcher = mock(TokenMatcher.class); when(tokenMatcher.matchToken(any(TokenQueue.class), anyList())).thenReturn(true); StatementChannel channel = StatementChannel.create(tokenMatcher); StatementChannelDisptacher dispatcher = new StatementChannelDisp...
public T multiply(BigDecimal multiplier) { return create(value.multiply(multiplier)); }
@Test void testMultiply() { final Resource resource = new TestResource(0.3); final BigDecimal by = BigDecimal.valueOf(0.2); assertTestResourceValueEquals(0.06, resource.multiply(by)); }
@Override public HttpResponseOutputStream<File> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String location = new StoregateWriteFeature(session, fileid).start(file, status); final MultipartOutputStream proxy = new Multipar...
@Test public void testWriteSingleByte() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), ...
static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure { if (!a.exists()) { throw new IllegalArgumentException("File [" + a + "] does not exist."); } if (!b.exists()) { throw new IllegalArgumentException("File [" + b + "] does not exist."); ...
@Test public void filesOnSameFolderShouldBeOnTheSameFileStore() throws RolloverFailure, IOException { if (!EnvUtil.isJDK7OrHigher()) return; File parent = new File(pathPrefix); File file = new File(pathPrefix + "filesOnSameFolderShouldBeOnTheSameFileStore"); FileUtil.cre...
@Override public Optional<RawFlag> fetch(FlagId id, FetchVector vector) { return sources.stream() .map(source -> source.fetch(id, vector)) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); }
@Test void test() { FlagSource source1 = mock(FlagSource.class); FlagSource source2 = mock(FlagSource.class); OrderedFlagSource orderedSource = new OrderedFlagSource(source1, source2); FlagId id = new FlagId("id"); FetchVector vector = new FetchVector(); when(source...
public void addTimeline(TimelineEvent event) { timeline.add(event); }
@Test public void testAddTimeline() { WorkflowRuntimeSummary summary = new WorkflowRuntimeSummary(); TimelineEvent event = TimelineLogEvent.info("hello world"); summary.addTimeline(event); assertEquals(Collections.singletonList(event), summary.getTimeline().getTimelineEvents()); }