focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@SuppressWarnings({"unchecked", "UnstableApiUsage"}) @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement) { if (!(statement.getStatement() instanceof DropStatement)) { return statement; } final DropStatement dropStatement = (DropState...
@Test public void shouldNotDeleteSchemaInSRIfNotSRSupported() throws IOException, RestClientException { // Given: when(topic.getValueFormat()).thenReturn(ValueFormat.of(FormatInfo.of(FormatFactory.DELIMITED.name()), SerdeFeatures.of())); // When: deleteInjector.inject(DROP_WITH_DELETE_TOPIC);...
@Override public String getName() { return _name; }
@Test public void testStringStartsWithTransformFunction() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("starts_with(%s, 'A')", STRING_ALPHANUM_SV_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue...
public static List<String> colTypesFromSchema(final String schema) { return splitAcrossOneLevelDeepComma(schema).stream() .map(RowUtil::removeBackTickAndKeyTrim) .map(RowUtil::splitAndGetSecond) .collect(Collectors.toList()); }
@Test public void shouldGetColumnTypesFromSchema() { // Given final String schema = "`K` STRUCT<`F1` ARRAY<STRING>>, " + "`STR` STRING, " + "`LONG` BIGINT, " + "`DEC` DECIMAL(4, 2)," + "`BYTES_` BYTES, " + "`ARRAY` ARRAY<STRING>, " + "`MA...
@Override public boolean rejoinNeededOrPending() { if (!subscriptions.hasAutoAssignedPartitions()) return false; // we need to rejoin if we performed the assignment and metadata has changed; // also for those owned-but-no-longer-existed partitions we should drop them as lost ...
@Test public void testDisconnectInJoin() { subscriptions.subscribe(singleton(topic1), Optional.of(rebalanceListener)); final List<TopicPartition> owned = Collections.emptyList(); final List<TopicPartition> assigned = singletonList(t1p); client.prepareResponse(groupCoordinatorRespons...
@Override public String toString(final RouteUnit routeUnit) { return identifier.getQuoteCharacter().wrap(getConstraintValue(routeUnit)); }
@Test void assertToString() { assertThat(new ConstraintToken(0, 1, new IdentifierValue("uc"), mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class).defaultAnswer(RETURNS_DEEP_STUBS)), mock(ShardingRule.class)).toString(getRouteUnit()), is("uc")); }
public static FingerprintTrustManagerFactoryBuilder builder(String algorithm) { return new FingerprintTrustManagerFactoryBuilder(algorithm); }
@Test public void testWithNoFingerprints() { assertThrows(IllegalStateException.class, new Executable() { @Override public void execute() { FingerprintTrustManagerFactory.builder("SHA-256").build(); } }); }
private ArrayAccess() { }
@Test public void shouldReturnNullOnNegativeOutOfBoundsIndex() { // Given: final List<Integer> list = ImmutableList.of(1, 2); // When: final Integer access = ArrayAccess.arrayAccess(list, -3); // Then: assertThat(access, nullValue()); }
public static String getSpnegoKeytabKey(Configuration conf, String defaultKey) { String value = conf.get(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY); return (value == null || value.isEmpty()) ? defaultKey : DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY; }
@Test(timeout=5000) public void testGetSpnegoKeytabKey() { HdfsConfiguration conf = new HdfsConfiguration(); String defaultKey = "default.spengo.key"; conf.unset(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY); assertEquals("Test spnego key in config is null", defaultKey, DFSUtil.get...
private double calcDistance(ReaderWay way, WaySegmentParser.CoordinateSupplier coordinateSupplier) { LongArrayList nodes = way.getNodes(); // every way has at least two nodes according to our acceptWay function GHPoint3D prevPoint = coordinateSupplier.getCoordinate(nodes.get(0)); if (pre...
@Test public void testDoNotRejectEdgeIfFirstNodeIsMissing_issue2221() { GraphHopper hopper = new GraphHopperFacade("test-osm9.xml").importOrLoad(); BaseGraph graph = hopper.getBaseGraph(); assertEquals(2, graph.getNodes()); assertEquals(1, graph.getEdges()); AllEdgesIterator ...
protected static String getReverseZoneNetworkAddress(String baseIp, int range, int index) throws UnknownHostException { if (index < 0) { throw new IllegalArgumentException( String.format("Invalid index provided, must be positive: %d", index)); } if (range < 0) { throw new Illegal...
@Test public void testGetReverseZoneNetworkAddress() throws Exception { assertEquals("172.17.4.0", ReverseZoneUtils.getReverseZoneNetworkAddress(NET, RANGE, INDEX)); }
static boolean shouldUpdate(AmazonInfo newInfo, AmazonInfo oldInfo) { if (newInfo.getMetadata().isEmpty()) { logger.warn("Newly resolved AmazonInfo is empty, skipping an update cycle"); } else if (!newInfo.equals(oldInfo)) { if (isBlank(newInfo.get(AmazonInfo.MetaDataKey.instance...
@Test public void testAmazonInfoUpdatePositiveCase() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = copyAmazonInfo(instanceInfo); newInfo.getMetadata().remove(amiId.getName()); assertThat(newInfo.getMetadata().size(), is(oldInfo.getMetadat...
public static int getPortFromEnvOrStartup(String[] args) { int port = 0; if (args != null && args.length >= 2) { for (int i = 0; i < args.length; ++i) { if ("-p".equalsIgnoreCase(args[i]) && i < args.length - 1) { port = NumberUtils.toInt(args[i + 1], 0); ...
@Test public void testGetPortFromEnvOrStartup() { Assertions.assertEquals(0,PortHelper.getPortFromEnvOrStartup(new String[]{})); }
@Override public String toString() { return "CmdbContext{" + "consumer=" + consumer + ", providers=" + providers + '}'; }
@Test void testToString() { CmdbContext<Instance> cmdbContext = new CmdbContext<>(); cmdbContext.setProviders(Collections.singletonList(new CmdbContext.CmdbInstance<>())); cmdbContext.setConsumer(new CmdbContext.CmdbInstance<>()); System.out.println(cmdbContext.toString()); a...
@Override public Long getUnreadNotifyMessageCount(Long userId, Integer userType) { return notifyMessageMapper.selectUnreadCountByUserIdAndUserType(userId, userType); }
@Test public void testGetUnreadNotifyMessageCount() { SqlConstants.init(DbType.MYSQL); // mock 数据 NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> { // 等会查询到 o.setUserId(1L); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setReadSt...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } final SMBSession.DiskShareWrapper share = session.openShare(file); try { if(new SMBPathCo...
@Test public void testFindFile() throws Exception { final Path test = new SMBTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); final SMBAttributesFinde...
@Nullable public Float getFloatValue(@FloatFormat final int formatType, @IntRange(from = 0) final int offset) { if ((offset + getTypeLen(formatType)) > size()) return null; switch (formatType) { case FORMAT_SFLOAT -> { if (mValue[offset + 1] == 0x07 && mValue[offset] == (byte) 0xFE) return F...
@Test public void setValue_SFLOAT_roundUp() { final MutableData data = new MutableData(new byte[2]); data.setValue(123.45f, Data.FORMAT_SFLOAT, 0); final float value = data.getFloatValue(Data.FORMAT_SFLOAT, 0); assertEquals(123.5f, value, 0.00); }
@Override public Credentials configure(final Host host) { if(StringUtils.isNotBlank(host.getHostname())) { final Credentials credentials = new Credentials(host.getCredentials()); configuration.refresh(); // Update this host credentials from the OpenSSH configuration file ...
@Test public void testConfigureDefaultKey() { OpenSSHCredentialsConfigurator c = new OpenSSHCredentialsConfigurator( new OpenSshConfig( new Local("src/main/test/resources", "openssh/config"))); final Credentials credentials = c.configure(new Host(new TestProtocol(Scheme.s...
public void publish(DefaultGoPublisher goPublisher, String destPath, File source, JobIdentifier jobIdentifier) { if (!source.exists()) { String message = "Failed to find " + source.getAbsolutePath(); goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message); bomb(message)...
@Test public void shouldBombWithErrorWhenStatusCodeReturnedIsRequestEntityTooLarge() throws IOException { when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class))).thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); CircularFifoQueue buffer ...
@Override public YamlModeConfiguration swapToYamlConfiguration(final ModeConfiguration data) { YamlModeConfiguration result = new YamlModeConfiguration(); result.setType(data.getType()); if (null != data.getRepository()) { YamlPersistRepositoryConfigurationSwapper<PersistReposito...
@Test void assertSwapToYamlConfiguration() { YamlModeConfiguration actual = swapper.swapToYamlConfiguration(new ModeConfiguration("TEST_TYPE", null)); assertThat(actual.getType(), is(TEST_TYPE)); }
@Override public Server build(Environment environment) { printBanner(environment.getName()); final ThreadPool threadPool = createThreadPool(environment.metrics()); final Server server = buildServer(environment.lifecycle(), threadPool); final Handler applicationHandler = createAppServ...
@Test void doesNotDefaultDetailedJsonProcessingExceptionToFalse() { http.setDetailedJsonProcessingExceptionMapper(true); http.build(environment); assertThat(environment.jersey().getResourceConfig().getSingletons()) .filteredOn(x -> x instanceof ExceptionMapperBinder) ...
@Override public ParDoFn create( PipelineOptions options, CloudObject cloudUserFn, List<SideInputInfo> sideInputInfos, TupleTag<?> mainOutputTag, Map<TupleTag<?>, Integer> outputTupleTagsToReceiverIndices, DataflowExecutionContext<?> executionContext, DataflowOperationContext...
@Test public void testCreateUnknownParDoFn() throws Exception { // A bogus serialized DoFn CloudObject cloudUserFn = CloudObject.forClassName("UnknownKindOfDoFn"); try { DEFAULT_FACTORY.create( DEFAULT_OPTIONS, cloudUserFn, null, MAIN_OUTPUT, Immutab...
@NonNull @VisibleForTesting static String[] getPermissionsStrings(int requestCode) { switch (requestCode) { case CONTACTS_PERMISSION_REQUEST_CODE -> { return new String[] {Manifest.permission.READ_CONTACTS}; } case NOTIFICATION_PERMISSION_REQUEST_CODE -> { if (Build.VERSION.SDK_I...
@Test @Config(sdk = TIRAMISU) public void testGetPermissionsStringsNotificationsNewDevice() { Assert.assertArrayEquals( new String[] {Manifest.permission.POST_NOTIFICATIONS}, PermissionRequestHelper.getPermissionsStrings( PermissionRequestHelper.NOTIFICATION_PERMISSION_REQUEST_CODE))...
public boolean isNewerThan(JavaSpecVersion otherVersion) { return this.compareTo(otherVersion) > 0; }
@Test public void test17newerThan11() throws Exception { // Setup fixture. final JavaSpecVersion eleven = new JavaSpecVersion( "11" ); final JavaSpecVersion seventeen = new JavaSpecVersion( "17" ); // Execute system under test. final boolean result = seventeen.isNewerTha...
public B appendParameters(Map<String, String> appendParameters) { this.parameters = appendParameters(parameters, appendParameters); return getThis(); }
@Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); MethodBuilder builder = new MethodBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build()....
@Override public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException { // Now only support sync invoke. if (request.getInvokeType() != null && !RpcConstants.INVOKER_TYPE_SYNC.equals(request.getInvokeType())) { return invoker.invoke(request); } ...
@Test public void testInvokeSentinelWorks() { SentinelSofaRpcConsumerFilter filter = new SentinelSofaRpcConsumerFilter(); final String interfaceResourceName = "com.alibaba.csp.sentinel.adapter.sofa.rpc.service.DemoService"; final String methodResourceName = "com.alibaba.csp.sentinel.adapter...
@Override public void execute(ComputationStep.Context context) { for (TriggerViewRefreshDelegate triggerViewRefreshDelegate : this.triggerViewRefreshDelegates) { OptionalInt count = triggerViewRefreshDelegate.triggerFrom(analysisMetadata.getProject()); count.ifPresent(i -> context.getStatistics().add(...
@Test public void execute_has_no_effect_if_constructor_without_delegate() { TriggerViewRefreshStep underTest = new TriggerViewRefreshStep(analysisMetadataHolder); underTest.execute(new TestComputationStepContext()); verifyNoInteractions(analysisMetadataHolder); }
public static List<TypedExpression> coerceCorrectConstructorArguments( final Class<?> type, List<TypedExpression> arguments, List<Integer> emptyCollectionArgumentsIndexes) { Objects.requireNonNull(type, "Type parameter cannot be null as the method searches constructors from t...
@Test public void coerceCorrectConstructorArgumentsIsNotCollectionAtIndex() { final List<TypedExpression> arguments = List.of(new IntegerLiteralExpressionT(new IntegerLiteralExpr("12"))); Assertions.assertThatThrownBy( () -> MethodResolutionUtils.coerceCorrectConstructorArgum...
public void printKsqlEntityList(final List<KsqlEntity> entityList) { switch (outputFormat) { case JSON: printAsJson(entityList); break; case TABULAR: final boolean showStatements = entityList.size() > 1; for (final KsqlEntity ksqlEntity : entityList) { writer()....
@Test public void shouldPrintAssertTopicResult() { // Given: final KsqlEntityList entities = new KsqlEntityList(ImmutableList.of( new AssertTopicEntity("statement", "name", true) )); // When: console.printKsqlEntityList(entities); // Then: final String output = terminal.getOutput...
public int getIssueCount() throws IOException { Request request = new Request.Builder().url(url + "/issues.json").build(); Response response = client.newCall(request).execute(); JSONObject jsonObject = new JSONObject(response.body().string()); return jsonObject.getInt("total_count"); ...
@Test public void canGetIssueCount() throws Exception { RedmineClient redmineClient = new RedmineClient(redmineContainer.getRedmineUrl()); assertThat(redmineClient.getIssueCount()).as("The issue count can be retrieved.").isZero(); }
public static <K, V> Read<K, V> read() { return new AutoValue_KafkaIO_Read.Builder<K, V>() .setTopics(new ArrayList<>()) .setTopicPartitions(new ArrayList<>()) .setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN) .setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES) ...
@Test(expected = IllegalStateException.class) public void testWithInvalidConsumerPollingTimeout() { KafkaIO.<Integer, Long>read().withConsumerPollingTimeout(-5L); }
public void parse(File xmlFile) throws XMLStreamException { FileInputStream input = null; try { input = new FileInputStream(xmlFile); parse(input); } catch (FileNotFoundException e) { throw new XMLStreamException(e); } finally { IOUtils.closeQuietly(input); } }
@Test public void testXMLWithXSD() throws XMLStreamException { StaxParser parser = new StaxParser(getTestHandler()); parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/scanner/genericcoverage/xml-xsd-test.xml")); }
public static String buildPluginParentPath() { return String.join(PATH_SEPARATOR, PLUGIN_PARENT); }
@Test public void testBuildPluginParentPath() { String pluginParentPath = DefaultPathConstants.buildPluginParentPath(); assertThat(pluginParentPath, notNullValue()); assertThat(PLUGIN_PARENT, equalTo(pluginParentPath)); }
@Override public String getPrefix() { return String.format("%s.%s", GoogleStorageProtocol.class.getPackage().getName(), "GoogleStorage"); }
@Test public void testPrefix() { assertEquals("ch.cyberduck.core.googlestorage.GoogleStorage", new GoogleStorageProtocol().getPrefix()); }
@Override protected int getDefaultPort() { return FTP.DEFAULT_PORT; }
@Test public void testFTPDefaultPort() throws Exception { FTPFileSystem ftp = new FTPFileSystem(); assertEquals(FTP.DEFAULT_PORT, ftp.getDefaultPort()); }
@Override public synchronized KafkaMessageBatch fetchMessages(StreamPartitionMsgOffset startMsgOffset, int timeoutMs) { long startOffset = ((LongMsgOffset) startMsgOffset).getOffset(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Polling partition: {}, startOffset: {}, timeout: {}ms", _topicPartition, s...
@Test public void testOffsetsExpired() throws TimeoutException { Map<String, String> streamConfigMap = new HashMap<>(); streamConfigMap.put("streamType", "kafka"); streamConfigMap.put("stream.kafka.topic.name", TEST_TOPIC_3); streamConfigMap.put("stream.kafka.broker.list", _kafkaBrokerAddress); ...
@Override public HashSlotCursor12byteKey cursor() { return new CursorIntKey2(); }
@Test @RequireAssertEnabled public void testCursor_advance_afterAdvanceReturnsFalse() { insert(randomKey(), randomKey()); HashSlotCursor12byteKey cursor = hsa.cursor(); cursor.advance(); cursor.advance(); assertThrows(AssertionError.class, cursor::advance); }
public InetAddress getAddress() { return inetSocketAddress.getAddress(); }
@Test public void testGetAddress() throws Exception { final InetSocketAddress inetSocketAddress = new InetSocketAddress(Inet4Address.getLoopbackAddress(), 12345); final ResolvableInetSocketAddress address = new ResolvableInetSocketAddress(inetSocketAddress); assertThat(address.getAddress())...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testDodgyProtect1() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", PROTECT_1, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_DODGY_NECKLACE, 1); }
public static ADXSinkConfig load(String yamlFile) throws IOException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); return mapper.readValue(new File(yamlFile), ADXSinkConfig.class); }
@Test public final void loadFromMapTest() throws IOException { Map<String, Object> map = getConfig(); SinkContext sinkContext = Mockito.mock(SinkContext.class); ADXSinkConfig config = ADXSinkConfig.load(map, sinkContext); assertNotNull(config); assertEquals(config.getClusterU...
@Override public Deserializer deserializer(String topic, Target type) { return new Deserializer() { @SneakyThrows @Override public DeserializeResult deserialize(RecordHeaders headers, byte[] data) { try { UnknownFieldSet unknownFields = UnknownFieldSet.parseFrom(d...
@Test void deserializeInvalidMessage() { var deserializer = serde.deserializer(DUMMY_TOPIC, Serde.Target.VALUE); assertThatThrownBy(() -> deserializer.deserialize(null, new byte[] { 1, 2, 3 })) .isInstanceOf(ValidationException.class) .hasMessageContaining("Protocol message contained an invali...
protected static void configureMulticastSocket(MulticastSocket multicastSocket, Address bindAddress, HazelcastProperties hzProperties, MulticastConfig multicastConfig, ILogger logger) throws SocketException, IOException, UnknownHostException { multicastSocket.setReuseAddress(true); ...
@Test public void testSetInterfaceDefaultWhenNonLoopbackAddrAndLoopbackMode() throws Exception { Config config = createConfig(null); MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig(); multicastConfig.setLoopbackModeEnabled(true); MulticastSock...
@Override public void addInterface(VplsData vplsData, Interface iface) { requireNonNull(vplsData); requireNonNull(iface); VplsData newData = VplsData.of(vplsData); newData.addInterface(iface); updateVplsStatus(newData, VplsData.VplsState.UPDATING); }
@Test public void testAddInterface() { VplsData vplsData = vplsManager.createVpls(VPLS1, NONE); vplsManager.addInterface(vplsData, V100H1); vplsManager.addInterface(vplsData, V100H2); vplsData = vplsStore.getVpls(VPLS1); assertNotNull(vplsData); assertEquals(vplsData....
@Override public void execute(GraphModel graphModel) { Graph graph = graphModel.getGraphVisible(); execute(graph); }
@Test public void testColumnCreation() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1); WeightedDegree d = new WeightedDegree(); d.execute(graphModel); Assert.assertTrue(graphModel.getNodeTable().hasColumn(WeightedDegree.WDEGREE)); }
@SuppressWarnings("unchecked") @Override public boolean canHandleReturnType(Class returnType) { return rxSupportedTypes.stream() .anyMatch(classType -> classType.isAssignableFrom(returnType)); }
@Test public void testCheckTypes() { assertThat(rxJava2RetryAspectExt.canHandleReturnType(Flowable.class)).isTrue(); assertThat(rxJava2RetryAspectExt.canHandleReturnType(Single.class)).isTrue(); }
@Override @SuppressWarnings("DuplicatedCode") public Integer cleanJobLog(Integer exceedDay, Integer deleteLimit) { int count = 0; LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay); // 循环删除,直到没有满足条件的数据 for (int i = 0; i < Short.MAX_VALUE; i++) { int d...
@Test public void testCleanJobLog() { // mock 数据 JobLogDO log01 = randomPojo(JobLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3)))) .setExecuteIndex(1); jobLogMapper.insert(log01); JobLogDO log02 = randomPojo(JobLogDO.class, o -> o.setCreateTime(addTime(D...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testNewWatermarkNoFetch() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTestNewKey.state(NAMESPACE, addr); assertThat(bag.read(), Matchers.nullValue()); // Shou...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testShhGetMessages() throws Exception { web3j.shhGetMessages(Numeric.toBigInt("0x7")).send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"shh_getMessages\"," + "\"params\":[\"0x7\"],\"id\":1}"); }
public PullRequestStateProducer(GitHubEndpoint endpoint) throws Exception { super(endpoint); Registry registry = endpoint.getCamelContext().getRegistry(); Object service = registry.lookupByName(GitHubConstants.GITHUB_COMMIT_SERVICE); if (service != null) { LOG.debug("Using C...
@Test public void testPullRequestStateProducer() { commitsha = commitService.getNextSha(); Endpoint stateProducerEndpoint = getMandatoryEndpoint("direct:validPullRequest"); Exchange exchange = stateProducerEndpoint.createExchange(); String text = "Message sent at " + new Date(); ...
@Override @TpsControl(pointName = "ConfigPublish") @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) @ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class) public ConfigPublishResponse handle(ConfigPublishRequest request, RequestMeta meta) throws NacosException { ...
@Test void testBetaPublishNotCas() throws NacosException, InterruptedException { String dataId = "testBetaPublish"; String group = "group"; String tenant = "tenant"; String content = "content"; ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); ...
public static boolean isNullOrBlank(final CharSequence cs) { if (cs == null) { return true; } for (int c : cs.chars().toArray()) { if (!Character.isWhitespace(c)) { return false; } } return true; }
@Test public void testIsBlank() throws IOException { assertTrue(StringUtils.isNullOrBlank(null)); assertTrue(StringUtils.isNullOrBlank("")); assertTrue(StringUtils.isNullOrBlank(" ")); assertFalse(StringUtils.isNullOrBlank(" a ")); assertFalse(StringUtils.isNullOrBlank("abc")); }
@Override public MapperResult findAllConfigInfoFragment(MapperContext context) { String contextParameter = context.getContextParameter(ContextConstant.NEED_CONTENT); boolean needContent = contextParameter != null && Boolean.parseBoolean(contextParameter); return new MapperResult("SELECT id,d...
@Test void testFindAllConfigInfoFragment() { //with content context.putContextParameter(ContextConstant.NEED_CONTENT, "true"); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFragment(context); assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenan...
@Override public void getConfig(MetricsNodesConfig.Builder builder) { builder.node.addAll(MetricsNodesConfigGenerator.generate(getContainers())); }
@Test void cluster_is_prepared_so_that_application_metadata_config_is_produced() { VespaModel model = getModel(servicesWithAdminOnly(), self_hosted); ApplicationMetadataConfig config = model.getConfig(ApplicationMetadataConfig.class, CLUSTER_CONFIG_ID); assertEquals(MockApplicationPackage.AP...
public Map<String, Parameter> generateMergedStepParams( WorkflowSummary workflowSummary, Step stepDefinition, StepRuntime stepRuntime, StepRuntimeSummary runtimeSummary) { Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>(); // Start with default step level params if prese...
@Test public void testRestartConfigStepRunParamMergeOrder() { ((TypedStep) step) .setParams( twoItemMap( "p1", ParamDefinition.buildParamDefinition("p1", "d1"), "p2", ParamDefinition.buildParamDefinition("p2", "d2"))); Map<String, Map<String, ParamDefinitio...
public int size() { return records.stream().mapToInt(r -> r.size()).sum(); }
@Test public void emptyTreeShouldBeZeroSized() { assertEquals(0, new SObjectTree().size()); }
public Map<String, LdapContextFactory> getContextFactories() { if (contextFactories == null) { contextFactories = new LinkedHashMap<>(); String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { initMultiLdapConfiguration(serverKeys); } else { ...
@Test public void testContextFactoriesWithMultipleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig()); assertThat(settingsManager.getContextFactories()).hasSize(2); // We do it twice to make sure the settings keep ...
@Override public void accept(Props props) { if (isClusterEnabled(props)) { checkClusterProperties(props); } }
@Test public void accept_throws_MessageException_if_node_type_is_not_correct() { TestAppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "true", CLUSTER_NODE_TYPE.getKey(), "bla")); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); ...
public CharacterPosition getLastNonWhitespacePosition() { return _lastNonWhitespacePosition; }
@Test public void testGetLastNonWhitespacePosition() throws IOException { LineColumnNumberWriter writer = new LineColumnNumberWriter(new StringWriter()); writer.write("123"); Assert.assertEquals(writer.getLastNonWhitespacePosition(), new LineColumnNumberWriter.CharacterPosition(1, 3)); writer.write(...
public static String getProperty(String propertyName, String envName) { return System.getenv().getOrDefault(envName, System.getProperty(propertyName)); }
@Test void getPropertyWithDefaultValue() { String property = PropertyUtils.getProperty("nacos.test", "xx", "test001"); assertEquals("test001", property); }
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingUpdateStructRowToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "serverTransactionId", true, "1", "tableNam...
public static ColumnIndex build( PrimitiveType type, BoundaryOrder boundaryOrder, List<Boolean> nullPages, List<Long> nullCounts, List<ByteBuffer> minValues, List<ByteBuffer> maxValues) { return build(type, boundaryOrder, nullPages, nullCounts, minValues, maxValues, null, null); ...
@Test public void testStaticBuildDouble() { ColumnIndex columnIndex = ColumnIndexBuilder.build( Types.required(DOUBLE).named("test_double"), BoundaryOrder.UNORDERED, asList(false, false, false, false, false, false), asList(0l, 1l, 2l, 3l, 4l, 5l), toBBList(-1.0, -2.0, -3.0,...
@Override public String toString() { StringBuilder b = new StringBuilder(); if (StringUtils.isNotBlank(protocol)) { b.append(protocol); b.append("://"); } if (StringUtils.isNotBlank(host)) { b.append(host); } if (!isPortDefault() &&...
@Test public void testNonHttpProtocolNoPort() { s = "ftp://ftp.example.com/dir"; t = "ftp://ftp.example.com/dir"; assertEquals(t, new HttpURL(s).toString()); }
public static MocoEventAction get(final String url, final HttpHeader... headers) { return get(text(checkNotNullOrEmpty(url, "URL should not be null")), checkNotNull(headers, "Headers should not be null")); }
@Test public void should_throw_exception_for_unknown_request() { assertThrows(HttpResponseException.class, () -> running(server, () -> assertThat(helper.get(root()), is("bar")))); }
@Override protected void verifyConditions(ScesimModelDescriptor scesimModelDescriptor, ScenarioRunnerData scenarioRunnerData, ExpressionEvaluatorFactory expressionEvaluatorFactory, Map<String, Object> request...
@Test public void verifyConditions_noDecisionGeneratedForSpecificName() { // test 1 - no decision generated for specific decisionName ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpec...
@Override public double sd() { return Math.sqrt(r * (1 - p)) / p; }
@Test public void testSd() { System.out.println("sd"); NegativeBinomialDistribution instance = new NegativeBinomialDistribution(3, 0.3); instance.rand(); assertEquals(Math.sqrt(7/0.3), instance.sd(), 1E-7); }
@Override public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo, Set<String> authScopes) { Map<String, Object> result = newLinkedHashMap(); OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication(); result.put(ACTIVE, true); if (...
@Test public void shouldAssembleExpectedResultForRefreshToken() throws ParseException { // given OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L), oauth2AuthenticationWithUser(oauth2Request("clientId", scopes("foo", "bar")), "name")); UserInfo userInfo = userInfo("sub"); Set<St...
@GET @Path("{noteId}/revision") @ZeppelinApi public Response getNoteRevisionHistory(@PathParam("noteId") String noteId) throws IOException { LOGGER.info("Get revision history of note {}", noteId); List<NotebookRepoWithVersionControl.Revision> revisions = notebookService.listRevisionHistory(noteId, getServ...
@Test void testGetNoteRevisionHistory() throws IOException { LOG.info("Running testGetNoteRevisionHistory"); String note1Id = null; try { String notePath = "note1"; note1Id = notebook.createNote(notePath, anonymous); //Add a paragraph and commit NotebookRepoWithVersionControl.Revi...
@Override public void setConf(Configuration conf) { super.setConf(conf); getRawMapping().setConf(conf); }
@Test(timeout=60000) public void testBadFile() throws IOException { File mapFile = File.createTempFile(getClass().getSimpleName() + ".testBadFile", ".txt"); Files.asCharSink(mapFile, StandardCharsets.UTF_8).write("bad contents"); mapFile.deleteOnExit(); TableMapping mapping = new TableMapping(...
public FinalizedFeatures( MetadataVersion metadataVersion, Map<String, Short> finalizedFeatures, long finalizedFeaturesEpoch, boolean kraftMode ) { this.metadataVersion = metadataVersion; this.finalizedFeatures = new HashMap<>(finalizedFeatures); this.finalize...
@Test public void testKRaftModeFeatures() { FinalizedFeatures finalizedFeatures = new FinalizedFeatures(MINIMUM_KRAFT_VERSION, Collections.singletonMap("foo", (short) 2), 123, true); assertEquals(MINIMUM_KRAFT_VERSION.featureLevel(), finalizedFeatures.finalizedFeature...
public static byte[] compress(String urlString) throws MalformedURLException { byte[] compressedBytes = null; if (urlString != null) { // Figure the compressed bytes can't be longer than the original string. byte[] byteBuffer = new byte[urlString.length()]; int byteBu...
@Test public void testCompressWithSubdomains() throws MalformedURLException { String testURL = "http://www.forums.google.com"; byte[] expectedBytes = {0x00, 'f', 'o', 'r', 'u', 'm', 's', '.', 'g', 'o', 'o', 'g', 'l', 'e', 0x07}; assertTrue(Arrays.equals(expectedBytes, UrlBeaconUrlCompressor....
public static String fix(final String raw) { if ( raw == null || "".equals( raw.trim() )) { return raw; } MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( raw ); }
@Test public void testAdd__Handle__withNewLines() { final String result = KnowledgeHelperFixerTest.fixer.fix( "\n\t\n\tupdate( myObject );" ); assertEqualsIgnoreWhitespace( "\n\t\n\tdrools.update( myObject );", result ); }
public static List<UpdateRequirement> forReplaceView( ViewMetadata base, List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != base, "Invalid view metadata: null"); Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Build...
@Test public void emptyUpdatesForReplaceView() { assertThat(UpdateRequirements.forReplaceView(viewMetadata, ImmutableList.of())) .hasSize(1) .hasOnlyElementsOfType(UpdateRequirement.AssertViewUUID.class); }
@Override public String named() { return PluginEnum.DIVIDE.getName(); }
@Test public void namedTest() { assertEquals(PluginEnum.DIVIDE.getName(), dividePlugin.named()); }
public Map<String, String> getExtraInfo() { return extraInfo; }
@Test void getExtraInfo() {}
@Override @Transactional(rollbackFor = Exception.class) public void deleteCombinationActivity(Long id) { // 校验存在 CombinationActivityDO activity = validateCombinationActivityExists(id); // 校验状态 if (CommonStatusEnum.isEnable(activity.getStatus())) { throw exception(COMB...
@Test public void testDeleteCombinationActivity_success() { // mock 数据 CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class); combinationActivityMapper.insert(dbCombinationActivity);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbCombinationActivity.g...
public IsJson(Matcher<? super ReadContext> jsonMatcher) { this.jsonMatcher = jsonMatcher; }
@Test public void shouldMatchJsonStringEvaluatedToTrue() { assertThat(BOOKS_JSON_STRING, isJson(withPathEvaluatedTo(true))); }
public String getSha1sum() { if (sha1sum == null) { this.sha1sum = determineHashes(SHA1_HASHING_FUNCTION); } return this.sha1sum; }
@Test public void testGetSha1sum() { //File file = new File(this.getClass().getClassLoader().getResource("struts2-core-2.1.2.jar").getPath()); File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar"); Dependency instance = new Dependency(file); //String expResult = "89C...
@NonNull public HealthStateAggregator healthStateAggregator() { if (healthStateAggregator == null) { final String message = "Cannot access the HealthStateAggregator before HealthFactory setup has occurred"; LOGGER.error(message); throw new IllegalStateException(message); ...
@Test void gettingHealthStateAggregatorBeforeSetShouldResultInException() { assertThrows(IllegalStateException.class, () -> healthEnvironment.healthStateAggregator()); }
@GET @Path("config") public Response getAllPackageConfigs() { try { Map<String, Map<String, Object>> config = helium.getAllPackageConfig(); return new JsonResponse<>(Response.Status.OK, config).build(); } catch (RuntimeException e) { logger.error(e.getMessage(), e); return new JsonRe...
@Test void testGetAllPackageConfigs() throws IOException { CloseableHttpResponse get = httpGet("/helium/config/"); assertThat(get, isAllowed()); Map<String, Object> resp = gson.fromJson(EntityUtils.toString(get.getEntity(), StandardCharsets.UTF_8), new TypeToken<Map<String, Object>>() { }.getT...
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("transactionRole:"); sb.append(transactionRole.name()); sb.append(","); sb.append("address:"); sb.append(address); sb.append(","); sb.append("msg:< "); sb.ap...
@Test public void testToString() { String expectStr = "transactionRole:RMROLE,address:127.0.0.1:8091,msg:< " + MSG1.toString() + " >"; Assertions.assertEquals(nettyPoolKey.toString(), expectStr); }
public Page<ConnectionResponse> convertToConnectionResponse(Page<Connection> allConnections) { List<ConnectionResponse> convertedConnection = connectionMapper.toConnectionResponse(allConnections.getContent()); return new PageImpl<>(convertedConnection, allConnections.getPageable(), allConnections.getTot...
@Test void convertToConnectionResponse() { Page<ConnectionResponse> result = connectionServiceMock.convertToConnectionResponse(getPageConnections()); assertEquals(result.getTotalPages(), getPageConnections().getTotalPages()); assertNotNull(result); }
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_map_of_non_serializable_key() { Map<NonSerializableObject, String> original = new HashMap<>(); original.put(new NonSerializableObject("key"), "value"); Object cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSame(ori...
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingDeleteStructRowNewRowAndOldValuesToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "transactionId", false, "1", ...
@Override public CheckResult runCheck() { try { final String filter = buildQueryFilter(stream.getId(), query); // TODO we don't support cardinality yet final FieldStatsResult fieldStatsResult = searches.fieldStats(field, "*", filter, RelativeRange.create(t...
@Test public void testRunCheckLowerNegative() throws Exception { for (FieldValueAlertCondition.CheckType checkType : FieldValueAlertCondition.CheckType.values()) { final double threshold = 50.0; final double higherThanThreshold = threshold + 10; FieldValueAlertCondition f...
@Override public PageResult<SocialClientDO> getSocialClientPage(SocialClientPageReqVO pageReqVO) { return socialClientMapper.selectPage(pageReqVO); }
@Test public void testGetSocialClientPage() { // mock 数据 SocialClientDO dbSocialClient = randomPojo(SocialClientDO.class, o -> { // 等会查询到 o.setName("芋头"); o.setSocialType(SocialTypeEnum.GITEE.getType()); o.setUserType(UserTypeEnum.ADMIN.getValue()); o....
public static List<Event> computeEventDiff(final Params params) { final List<Event> events = new ArrayList<>(); emitPerNodeDiffEvents(createBaselineParams(params), events); emitWholeClusterDiffEvent(createBaselineParams(params), events); emitDerivedBucketSpaceStatesDiffEvents(params, ev...
@Test void node_down_edge_with_group_down_reason_has_separate_event_emitted() { // We sneakily use a flat cluster here but still use a 'group down' reason. Differ doesn't currently care. final EventFixture fixture = EventFixture.createForNodes(3) .clusterStateBefore("distributor:3 st...
public void scheduleUpdateIfAbsent(String serviceName, String groupName, String clusters) { if (!asyncQuerySubscribeService) { return; } String serviceKey = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters); if (futureMap.get(serviceKey) != null...
@Test void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetchForgetTopicIdWhenUnassigned() { buildFetcher(); TopicIdPartition foo = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0)); TopicIdPartition bar = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("bar", 0)); // Assign foo and b...
void patchIngressClassName(Ingress current, Ingress desired) { if (desired.getSpec() != null && current.getSpec() != null && desired.getSpec().getIngressClassName() == null) { desired.getSpec().setIngressClassName(current.getSpec().getIngressClassName()); } ...
@Test public void testIngressClassPatching() { KubernetesClient client = mock(KubernetesClient.class); Ingress current = new IngressBuilder() .withNewMetadata() .withNamespace(NAMESPACE) .withName(RESOURCE_NAME) .endMetadata()...
public Query initParams(Map<String, String> params) { if (MapUtil.isNotEmpty(params)) { for (Map.Entry<String, String> entry : params.entrySet()) { addParam(entry.getKey(), entry.getValue()); } } return this; }
@Test void testInitParams() { Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put(CommonParams.NAMESPACE_ID, "namespace"); parameters.put(CommonParams.SERVICE_NAME, "service"); parameters.put(CommonParams.GROUP_NAME, "group"); parameters.put(C...
@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 testSchemaLike() { run("schema-like.feature"); }
public void parse(String[] args) throws FileNotFoundException, ParseException { line = parseArgs(args); if (line != null) { validateArgs(); } }
@Test public void testParse() throws Exception { String[] args = {}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertFalse(instanc...
public static VerificationMode atLeast(final int count) { checkArgument(count > 0, "Times count must be greater than zero"); return new AtLeastVerification(count); }
@Test public void should_fail_to_verify_at_least_expected_request_while_expectation_can_not_be_met() { httpServer(port(), hit); assertThrows(VerificationException.class, () -> hit.verify(by(uri("/foo")), atLeast(1))); }
static void readFullyDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException { int nextReadLength = Math.min(buf.remaining(), temp.length); int bytesRead = 0; while (nextReadLength > 0 && (bytesRead = f.read(temp, 0, nextReadLength)) >= 0) { buf.put(temp, 0, bytesRead); next...
@Test public void testDirectReadFullyPositionAndLimit() throws Exception { final ByteBuffer readBuffer = ByteBuffer.allocateDirect(10); readBuffer.position(3); readBuffer.limit(7); readBuffer.mark(); MockInputStream stream = new MockInputStream(2, 3, 3); DelegatingSeekableInputStream.readFul...
@Override public boolean isDetected() { return "true".equals(system.envVariable("CI")) && "true".equals(system.envVariable("DRONE")); }
@Test public void isDetected() { setEnvVariable("CI", "true"); setEnvVariable("DRONE", "true"); assertThat(underTest.isDetected()).isTrue(); setEnvVariable("CI", "true"); setEnvVariable("DRONE", null); assertThat(underTest.isDetected()).isFalse(); }
public PipelineConfigs getFirstEditablePartOrNull() { for (PipelineConfigs part : parts) { if (isEditable(part)) return part; } return null; }
@Test public void shouldReturnFirstEditablePartWhenExists() { PipelineConfig pipe1 = PipelineConfigMother.pipelineConfig("pipeline1"); BasicPipelineConfigs part1 = new BasicPipelineConfigs(pipe1); part1.setOrigin(new FileConfigOrigin()); MergePipelineConfigs group = new MergePipelin...
public URL convert(String value) { if (isBlank(value)) { throw new ParameterException(getErrorString("a blank value", "a valid URL")); } try { return URLUtil.parseURL(value); } catch (IllegalArgumentException e) { throw new ParameterException(getError...
@Test(expected = ParameterException.class) public void nullValueThrowsParameterException() { converter.convert(null); }
@Override public void open(Map<String, Object> map, SinkContext sinkContext) throws Exception { try { val configV2 = InfluxDBSinkConfig.load(map, sinkContext); configV2.validate(); sink = new InfluxDBSink(); } catch (Exception e) { try { ...
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = "For InfluxDB V2:.*") public void openInvalidInfluxConfig() throws Exception { InfluxDBGenericRecordSink sink = new InfluxDBGenericRecordSink(); sink.open(new HashMap<>(), mock(SinkContext.class)); }
public static NamespaceName get(String tenant, String namespace) { validateNamespaceName(tenant, namespace); return get(tenant + '/' + namespace); }
@Test(expectedExceptions = IllegalArgumentException.class) public void namespace_nullNamespace() { NamespaceName.get("pulsar", "cluster", null); }
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) { this.jsonPath = jsonPath; this.resultMatcher = resultMatcher; }
@Test public void shouldMatchJsonPathEvaluatedToStringValue() { assertThat(BOOKS_JSON, withJsonPath(compile("$.store.bicycle.color"), equalTo("red"))); assertThat(BOOKS_JSON, withJsonPath(compile("$.store.book[2].title"), equalTo("Moby Dick"))); assertThat(BOOKS_JSON, withJsonPath("$.store.n...
@Override public JSONObject getSuperProperties() { return new JSONObject(); }
@Test public void getSuperProperties() { Assert.assertEquals(0, mSensorsAPI.getSuperProperties().length()); }