focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) throws Exception { if (ObjectHelper.isEmpty(remaining)) { throw new IllegalArgumentException("You must provide a channel for the Dynamic Router"); } ...
@Test void testCreateEndpoint() throws Exception { component.setCamelContext(context); Endpoint actualEndpoint = component.createEndpoint("dynamic-router:testname", "remaining", Collections.emptyMap()); assertEquals(endpoint, actualEndpoint); }
public long getBackendIdWithStarletPort(String host, int starletPort) { for (Backend backend : idToBackendRef.values()) { if (NetUtils.isSameIP(backend.getHost(), host) && backend.getStarletPort() == starletPort) { return backend.getId(); } } return -1L; ...
@Test public void testGetBackendIdWithStarletPort() throws Exception { Backend be = new Backend(10001, "newHost", 1000); be.setStarletPort(10001); service.addBackend(be); long backendId = service.getBackendIdWithStarletPort("newHost", 10001); Assert.assertEquals(be.getId(), b...
public SerializableFunction<T, Row> getToRowFunction() { return toRowFunction; }
@Test public void testWktProtoToRow() throws InvalidProtocolBufferException { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(WktMessage.getDescriptor()); SerializableFunction<DynamicMessage, Row> toRow = schemaProvider.getToRowFunction(); assertEquals(WKT_MESSAGE_ROW, toRow.apply(toDynami...
static XmlNode create(String xmlString) { try (InputStream stream = new ByteArrayInputStream(xmlString.getBytes(UTF_8))) { DocumentBuilderFactory dbf = XmlUtil.getNsAwareDocumentBuilderFactory(); Document doc = dbf.newDocumentBuilder().parse(stream); return new XmlNode(doc.ge...
@Test(expected = RuntimeException.class) public void parseError() { // given String xml = "malformed-xml"; // when XmlNode.create(xml); // then // throws exception }
@Override public String getTargetRestEndpointURL() { return "/jobs/:" + JobIDPathParameter.KEY + "/vertices/:" + JobVertexIdPathParameter.KEY + "/subtasks/:" + SubtaskIndexPathParameter.KEY + "/metrics"; }
@Test void testUrl() { assertThat(subtaskMetricsHeaders.getTargetRestEndpointURL()) .isEqualTo( "/jobs/:" + JobIDPathParameter.KEY + "/vertices/:" + JobVertexIdPathParamete...
public void setProviderInfos(List<ProviderInfo> providerInfos) { this.providerInfos = providerInfos; }
@Test public void setProviderInfos() throws Exception { ProviderGroup pg = new ProviderGroup("xxx", null); List list = pg.getProviderInfos(); Assert.assertNotNull(list); Assert.assertTrue(list.size() == 0); List<ProviderInfo> newps = new ArrayList<ProviderInfo>(); pg...
@Override protected SegmentConversionResult convert(PinotTaskConfig pinotTaskConfig, File indexDir, File workingDir) throws Exception { Map<String, String> configs = pinotTaskConfig.getConfigs(); String tableNameWithType = configs.get(MinionConstants.TABLE_NAME_KEY); String rawTableName = TableNameB...
@Test public void testConvert() throws Exception { PurgeTaskExecutor purgeTaskExecutor = new PurgeTaskExecutor(); purgeTaskExecutor.setMinionEventObserver(new MinionProgressObserver()); PinotTaskConfig pinotTaskConfig = new PinotTaskConfig(MinionConstants.PurgeTask.TASK_TYPE, Collections .si...
@Override public <KEY> URIMappingResult<KEY> mapUris(List<URIKeyPair<KEY>> requestUriKeyPairs) throws ServiceUnavailableException { if (requestUriKeyPairs == null || requestUriKeyPairs.isEmpty()) { return new URIMappingResult<>(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap...
@Test public void testUniversalStickiness() throws ServiceUnavailableException, URISyntaxException { int partitionCount = 4; int totalHostCount = 200; HashRingProvider ringProvider = createStaticHashRingProvider(totalHostCount, partitionCount, getHashFunction(true)); HashFunction<Request> hashFunct...
public com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration getPackageConfiguration(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_PACKAGE_CONFIGURATION, new DefaultPluginInteractionCallback<>() { @Override public com.thoughtworks...
@Test public void shouldTalkToPluginToGetPackageConfiguration() throws Exception { String expectedRequestBody = null; String expectedResponseBody = "{" + "\"key-one\":{}," + "\"key-two\":{\"default-value\":\"two\",\"part-of-identity\":true,\"secure\":true,\"required\...
@Override public Set<TopicPartition> getAllSubscribedPartitions(Consumer<?, ?> consumer) { Set<TopicPartition> allPartitions = new HashSet<>(); for (String topic : topics) { List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic); if (partitionInfoList != null) ...
@Test public void testFilterOnAbsentTopic() { String presentTopic = "present"; String absentTopic = "absent"; NamedTopicFilter filter = new NamedTopicFilter(presentTopic, absentTopic); when(consumerMock.partitionsFor(presentTopic)).thenReturn(Collections.singletonList(create...
public void fetch(DownloadAction downloadAction, URLService urlService) throws Exception { downloadChecksumFile(downloadAction, urlService.baseRemoteURL()); downloadArtifact(downloadAction, urlService.baseRemoteURL()); }
@Test public void shouldUnzipWhenFetchingFolder() throws Exception { ChecksumFileHandler checksumFileHandler = mock(ChecksumFileHandler.class); when(checksumFileHandler.handleResult(SC_OK, publisher)).thenReturn(true); File destOnAgent = new File("pipelines/cruise/", dest.getPath()); ...
public static boolean areCompatible(final SqlArgument actual, final ParamType declared) { return areCompatible(actual, declared, false); }
@Test public void shouldFailINonCompatibleSchemas() { assertThat(ParamTypes.areCompatible( SqlArgument.of(SqlTypes.STRING), ParamTypes.INTEGER, false), is(false)); assertThat(ParamTypes.areCompatible( SqlArgument.of(SqlTypes.STRING), GenericType.of("T"), ...
@Override public String toString() { String bounds = printExtendsClause() ? " extends " + joinTypeNames(upperBounds) : ""; return getClass().getSimpleName() + '{' + getName() + bounds + '}'; }
@Test public void toString_upper_bounded_by_single_bound() { @SuppressWarnings("unused") class BoundedBySingleBound<NAME extends String> { } JavaTypeVariable<JavaClass> typeVariable = new ClassFileImporter().importClass(BoundedBySingleBound.class).getTypeParameters().get(0); ...
public static Combine.BinaryCombineDoubleFn ofDoubles() { return new Min.MinDoubleFn(); }
@Test public void testMinDoubleFnInfinity() { testCombineFn( Min.ofDoubles(), Lists.newArrayList(Double.NEGATIVE_INFINITY, 2.0, 3.0, Double.POSITIVE_INFINITY), Double.NEGATIVE_INFINITY); }
protected String getFileName(double lat, double lon) { lon = 1 + (180 + lon) / LAT_DEGREE; int lonInt = (int) lon; lat = 1 + (60 - lat) / LAT_DEGREE; int latInt = (int) lat; if (Math.abs(latInt - lat) < invPrecision / LAT_DEGREE) latInt--; // replace String....
@Disabled @Test public void testGetEleHorizontalBorder() { // Border between the tiles N42E011 and N42E012 assertEquals("srtm_38_04", instance.getFileName(44.94, 9.999999)); assertEquals(48, instance.getEle(44.94, 9.999999), precision); assertEquals("srtm_39_04", instance.getFile...
@Override protected TableRecords getUndoRows() { return sqlUndoLog.getAfterImage(); }
@Test public void getUndoRows() { OracleUndoInsertExecutor executor = upperCase(); Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getAfterImage()); }
public static DocumentBuilderFactory newSecureDocumentBuilderFactory() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setFeature(DISALLOW_DOCTYPE_DECL, true); dbf.setFeat...
@Test(expected = SAXException.class) public void testExternalDtdWithSecureDocumentBuilderFactory() throws Exception { DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) { Document doc = db.parse(stre...
public alluxio.grpc.WorkerIdentity toProto() { return Parsers.toProto(this); }
@Test public void parserToProto() throws Exception { byte[] idBytes = BufferUtils.getIncreasingByteArray(16); WorkerIdentity identity = new WorkerIdentity(idBytes, 1); alluxio.grpc.WorkerIdentity proto = WorkerIdentity.Parsers.toProto(identity); assertEquals(1, proto.getVersion()); assertArrayEqua...
@SuppressWarnings("unchecked") public static <T> Collection<T> getServiceInstances(final Class<T> serviceInterface) { return (Collection<T>) getRegisteredSPI(serviceInterface).getServiceInstances(); }
@Test void assertGetServiceInstancesWithEmptyInstances() { assertTrue(ShardingSphereServiceLoader.getServiceInstances(EmptySPIFixture.class).isEmpty()); }
public String getServiceKey() { if (serviceKey != null) { return serviceKey; } String inf = getServiceInterface(); if (inf == null) { return null; } serviceKey = buildKey(inf, getGroup(), getVersion()); return serviceKey; }
@Test void testGetServiceKey() { URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url1.getServiceKey()); URL url2 = URL.valueOf( ...
public static SingleInputSemanticProperties addSourceFieldOffset( SingleInputSemanticProperties props, int numInputFields, int offset) { SingleInputSemanticProperties offsetProps = new SingleInputSemanticProperties(); if (props.getReadFields(0) != null) { FieldSet offsetReadFiel...
@Test void testAddSourceFieldOffset() { SingleInputSemanticProperties semProps = new SingleInputSemanticProperties(); semProps.addForwardedField(0, 1); semProps.addForwardedField(0, 4); semProps.addForwardedField(2, 0); semProps.addForwardedField(4, 3); semProps.addR...
@Override public void initialize(PulsarService pulsarService) throws Exception { final ClassLoader previousContext = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(narClassLoader); this.interceptor.initialize(pulsarService);...
@Test public void testWrapper() throws Exception { BrokerInterceptor h = mock(BrokerInterceptor.class); NarClassLoader loader = mock(NarClassLoader.class); BrokerInterceptorWithClassLoader wrapper = new BrokerInterceptorWithClassLoader(h, loader); PulsarService pulsarService = mock(...
@Override public void startScheduling() { executorService.scheduleWithFixedDelay(this::cleanCeQueue, ceConfiguration.getCleanTasksInitialDelay(), ceConfiguration.getCleanTasksDelay(), MINUTES); }
@Test public void startScheduling_calls_cleaning_methods_of_internalCeQueue_at_fixed_rate_with_value_from_CeConfiguration() { InternalCeQueue mockedInternalCeQueue = mock(InternalCeQueue.class); long wornOutInitialDelay = 10L; long wornOutDelay = 20L; long unknownWorkerInitialDelay = 11L; long unk...
public static L3ModificationInstruction modArpSpa(IpAddress addr) { checkNotNull(addr, "Src l3 ARP IP address cannot be null"); return new ModArpIPInstruction(L3SubType.ARP_SPA, addr); }
@Test public void testModArpSpaMethod() { final Instruction instruction = Instructions.modArpSpa(ip41); final L3ModificationInstruction.ModArpIPInstruction modArpIPInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, ...
public static String escapeLuceneQuery(final CharSequence text) { if (text == null) { return null; } final int size = text.length() << 1; final StringBuilder buf = new StringBuilder(size); appendEscapedLuceneQuery(buf, text); return buf.toString(); }
@Test public void testEscapeLuceneQuery() { CharSequence text = "test encoding + - & | ! ( ) { } [ ] ^ \" ~ * ? : \\"; String expResult = "test encoding \\+ \\- \\& \\| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\\" \\~ \\* \\? \\: \\\\"; String result = LuceneUtils.escapeLuceneQuery(text); as...
public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (actual == null) { failWithActual("expected instance of", clazz.getName()); return; } if (!isInstanceOfType(actual, clazz)) { if (Platform.classMetadataUnsupported())...
@Test public void isInstanceOfInterfaceForNull() { expectFailure.whenTesting().that((Object) null).isInstanceOf(CharSequence.class); }
abstract void execute(Admin admin, Namespace ns, PrintStream out) throws Exception;
@Test public void testFindHangingNoMappedTransactionalId() throws Exception { TopicPartition topicPartition = new TopicPartition("foo", 5); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "find-hanging", "--topic", to...
public static String hadoopFsListAsString(String files, Configuration conf, String user) throws URISyntaxException, FileNotFoundException, IOException, InterruptedException { if (files == null || conf == null) { return null; } return StringUtils.arrayToString(hadoopFsLi...
@Test public void testHadoopFsListAsString() { try { String tmpFileName1 = "/tmp/testHadoopFsListAsString1"; String tmpFileName2 = "/tmp/testHadoopFsListAsString2"; File tmpFile1 = new File(tmpFileName1); File tmpFile2 = new File(tmpFileName2); tmpFile1.createNewFile(); tmpFile...
@Override public void set(Map<String, ?> buckets) { commandExecutor.get(setAsync(buckets)); }
@Test public void testSetWithPath() { RJsonBuckets buckets = redisson.getJsonBuckets(new JacksonCodec<>(TestType.class)); Map<String, Object> map = new HashMap<>(); IntStream.range(0, 1000).forEach(i -> { TestType testType = new TestType(); testType.setName("name" + i...
@Override public List<TScanRangeLocations> getScanRangeLocations(long maxScanRangeLength) { return result; }
@Test public void testGetScanRangeLocations() throws Exception { List<Column> columns = Lists.newArrayList(new Column("k1", INT), new Column("k2", INT)); IcebergTable icebergTable = new IcebergTable(1, "srTableName", "iceberg_catalog", "resource_name", "iceberg_db", "iceberg_table", ...
static byte[] longTo4ByteArray(long n) { byte[] bytes = Arrays.copyOfRange(ByteBuffer.allocate(8).putLong(n).array(), 4, 8); assert bytes.length == 4 : bytes.length; return bytes; }
@Test public void testLongToByteArray() { byte[] bytes = HDUtils.longTo4ByteArray(1026); assertEquals("00000402", ByteUtils.formatHex(bytes)); }
@Override public void deleteTenantPackage(Long id) { // 校验存在 validateTenantPackageExists(id); // 校验正在使用 validateTenantUsed(id); // 删除 tenantPackageMapper.deleteById(id); }
@Test public void testDeleteTenantPackage_used() { // mock 数据 TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class); tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbTenantPackage.getId(); // mock 租户在使用该套餐 when...
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (paddi...
@Test public void shouldPadEmptyInputBytes() { final ByteBuffer result = udf.lpad(EMPTY_BYTES, 4, BYTES_45); assertThat(result, is(ByteBuffer.wrap(new byte[]{4,5,4,5}))); }
private static boolean ipV6Check(byte[] ip) { if (ip.length != 16) { throw new RuntimeException("illegal ipv6 bytes"); } InetAddressValidator validator = InetAddressValidator.getInstance(); return validator.isValidInet6Address(ipToIPv6Str(ip)); }
@Test public void testIPv6Check() throws UnknownHostException { InetAddress nonInternal = InetAddress.getByName("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A"); InetAddress internal = InetAddress.getByName("FE80:0000:0000:0000:0000:0000:0000:FFFF"); assertThat(UtilAll.isInternalV6IP(nonInternal))...
@Override public void execute(Runnable command) { internalExecutor.execute(command); }
@Test public void testExecuteInternal() { TestRunnable runnable = new TestRunnable(); executionService.execute(runnable); runnable.await(); }
public CompletableFuture<SendPushNotificationResult> sendRateLimitChallengeNotification(final Account destination, final String challengeToken) throws NotPushRegisteredException { final Device device = destination.getPrimaryDevice(); final Pair<String, PushNotification.TokenType> tokenAndType = getToken(...
@Test void sendRateLimitChallengeNotification() throws NotPushRegisteredException { final Account account = mock(Account.class); final Device device = mock(Device.class); final String deviceToken = "token"; final String challengeToken = "challenge"; when(device.getId()).thenReturn(Device.PRIMARY...
@Override public List<QueuedCommand> getNewCommands(final Duration timeout) { completeSatisfiedSequenceNumberFutures(); final List<QueuedCommand> commands = Lists.newArrayList(); final Iterable<ConsumerRecord<byte[], byte[]>> records = commandTopic.getNewCommands(timeout); for (ConsumerRecord<byte[]...
@Test public void shouldCompleteFuturesWhenGettingNewCommands() { // Given: when(commandTopic.getCommandTopicConsumerPosition()).thenReturn(22L); // When: commandStore.getNewCommands(NEW_CMDS_TIMEOUT); // Then: final InOrder inOrder = inOrder(sequenceNumberFutureStore, commandTopic); inO...
public static Short max(Short a, Short b) { return a >= b ? a : b; }
@Test void testMax() { assertThat(summarize(-1000, 0, 1, 50, 999, 1001).getMax().shortValue()) .isEqualTo((short) 1001); assertThat(summarize((int) Short.MIN_VALUE, -1000, 0).getMax().shortValue()).isZero(); assertThat(summarize(1, 8, 7, 6, 9, 10, 2, 3, 5, 0, 11, -2, 3).getMa...
@Nonnull public static ToConverter getToConverter(QueryDataType type) { if (type.getTypeFamily() == QueryDataTypeFamily.OBJECT) { // User-defined types are subject to the same conversion rules as ordinary OBJECT. type = QueryDataType.OBJECT; } return Objects.requireNo...
@Test public void test_zonedDateTimeConversion() { OffsetDateTime time = OffsetDateTime.of(2020, 9, 8, 11, 4, 0, 0, UTC); Object converted = getToConverter(TIMESTAMP_WITH_TZ_ZONED_DATE_TIME).convert(time); assertThat(converted).isEqualTo(time.toZonedDateTime()); }
public static List<FieldInfo> buildSourceSchemaEntity(final LogicalSchema schema) { final List<FieldInfo> allFields = schema.columns().stream() .map(EntityUtil::toFieldInfo) .collect(Collectors.toList()); if (allFields.isEmpty()) { throw new IllegalArgumentException("Root schema should co...
@Test public void shouldNotExposeMetaColumns() { // Given: final LogicalSchema schema = LogicalSchema.builder() .valueColumn(ColumnName.of("bob"), SqlTypes.STRING) .build(); // When: final List<FieldInfo> fields = EntityUtil.buildSourceSchemaEntity(schema); // Then: assertTha...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "overridden generic resource methods operationId") public void testTicket3426() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Ticket3426Resource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /inher...
@Override public String getAuthMethodName() { return AUTH_METHOD_NAME; }
@Test public void testGetAuthMethodName() { assertEquals(this.auth.getAuthMethodName(), "token"); }
@Override public void connect() throws IllegalStateException, IOException { if (isConnected()) { throw new IllegalStateException("Already connected"); } InetSocketAddress address = this.address; // the previous dns retry logic did not work, as address.getAddress would alw...
@Test public void connectsToGraphiteWithInetSocketAddress() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { graphite.connect(); } verify(socketFactory).createSocket(address.getAddress(), address.getPort()); }
@Override public boolean hasNext() { if (currentIndex < currentData.size()) { return true; } if (currentPageable == null) { return false; } currentData = loadData(); currentIndex = 0; return !currentData.isEmpty(); }
@Test @SuppressWarnings("unchecked") void testConstructor_loadsData() { Page<Extension> page = mock(Page.class); when(page.getContent()).thenReturn(List.of(mock(Extension.class))); when(page.hasNext()).thenReturn(true); when(page.nextPageable()).thenReturn( PageReques...
public int getServerSocketBacklog() { return serverSocketBacklog; }
@Test public void testChangeConfigBySystemProperty() { System.setProperty(NettySystemConfig.COM_ROCKETMQ_REMOTING_SOCKET_BACKLOG, "65535"); NettySystemConfig.socketBacklog = Integer.parseInt(System.getProperty(NettySystemConfig.COM_ROCKETMQ_REMOTING_SOCKET_BACKLOG, "1024")); ...
public static <K, V, S extends StateStore> Materialized<K, V, S> as(final DslStoreSuppliers storeSuppliers) { Objects.requireNonNull(storeSuppliers, "store type can't be null"); return new Materialized<>(storeSuppliers); }
@Test public void shouldThrowNullPointerIfSessionBytesStoreSupplierIsNull() { final NullPointerException e = assertThrows(NullPointerException.class, () -> Materialized.as((SessionBytesStoreSupplier) null)); assertEquals(e.getMessage(), "supplier can't be null"); }
@SafeVarargs public static <T> T[] create(T... args) { return args; }
@Test public void testCreate() { assertArrayEquals(create("a"), (new String[] {"a"})); assertArrayEquals(create(""), (new String[] {""})); assertArrayEquals(create("a", "b"), (new String[] {"a", "b"})); }
public MetricsBuilder enableMetadata(Boolean enableMetadata) { this.enableMetadata = enableMetadata; return getThis(); }
@Test void enableMetadata() { MetricsBuilder builder = MetricsBuilder.newBuilder(); builder.enableMetadata(true); Assertions.assertTrue(builder.build().getEnableMetadata()); }
@Override public void handle(HttpExchange httpExchange) throws IOException { Optional<Boolean> operatorsAreReady = areOperatorsStarted(operators); if (operatorsAreReady.isEmpty() || !operatorsAreReady.get()) { sendMessage(httpExchange, HTTP_BAD_REQUEST, "spark operators are not ready yet"); } i...
@Test void testHandleSucceed() throws IOException { Operator operator = mock(Operator.class); Operator sparkConfMonitor = mock(Operator.class); RuntimeInfo runtimeInfo = mock(RuntimeInfo.class); RuntimeInfo sparkConfMonitorRuntimeInfo = mock(RuntimeInfo.class); when(operator.getRuntimeInfo()).then...
@Override public Iterator iterator() { if (entries == null) { return Collections.emptyIterator(); } return new ResultIterator(); }
@Test public void testIterator_whenNotEmpty_IterationType_Key() { List<Map.Entry> entries = new ArrayList<>(); MapEntrySimple entry = new MapEntrySimple("key", "value"); entries.add(entry); ResultSet resultSet = new ResultSet(entries, IterationType.KEY); Iterator iterator = r...
@Converter(fallback = true) public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (NodeInfo.class.isAssignableFrom(value.getClass())) { // use a fallback type converter so we can convert the embedded body if the value is NodeInfo ...
@Test public void convertToNodeAndByteArray() { Node node = context.getTypeConverter().convertTo(Node.class, exchange, doc); assertNotNull(node); byte[] ba = context.getTypeConverter().convertTo(byte[].class, exchange, node); assertNotNull(ba); String string = context.getType...
public static Serializer getSerializer(String alias) { // 工厂模式 托管给ExtensionLoader return EXTENSION_LOADER.getExtension(alias); }
@Test public void getSerializer() { Serializer serializer = SerializerFactory.getSerializer((byte) 117); Assert.assertNotNull(serializer); Assert.assertEquals(TestSerializer.class, serializer.getClass()); }
@Override public BeamSqlTable buildBeamSqlTable(Table table) { Schema schema = table.getSchema(); ObjectNode properties = table.getProperties(); Optional<ParsedLocation> parsedLocation = Optional.empty(); if (!Strings.isNullOrEmpty(table.getLocation())) { parsedLocation = Optional.of(parseLocat...
@Test public void testBuildBeamSqlNestedThriftTable() { Table table = mockNestedThriftTable("hello", SimpleThriftMessage.class, TCompactProtocol.Factory.class); BeamSqlTable sqlTable = provider.buildBeamSqlTable(table); assertNotNull(sqlTable); assertTrue(sqlTable instanceof NestedPayloadKafk...
public String name() { return name; }
@Test void name() { LocalPredictionId retrieved = new LocalPredictionId(fileName, name); assertThat(retrieved.name()).isEqualTo(name); }
void registerColumnFamily(String columnFamilyName, ColumnFamilyHandle handle) { boolean columnFamilyAsVariable = options.isColumnFamilyAsVariable(); MetricGroup group = columnFamilyAsVariable ? metricGroup.addGroup(COLUMN_FAMILY_KEY, columnFamilyName) ...
@Test void testReturnsUnsigned() throws Throwable { ForStExtension localForStExtension = new ForStExtension(); localForStExtension.before(); SimpleMetricRegistry registry = new SimpleMetricRegistry(); GenericMetricGroup group = new GenericMetricGroup( ...
public static void minValueCheck(String name, Long value, long min) { if (value < min) { throw new IllegalArgumentException(name + " cannot be less than <" + min + ">!"); } }
@Test public void testMinValueCheck() { assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.minValueCheck("param1", 9L, 10L)); ValueValidationUtil.minValueCheck("param2", 10L, 10L); ValueValidationUtil.minValueCheck("param3", 11L, 10L); }
@Override protected Trigger getContinuationTrigger(List<Trigger> continuationTriggers) { return this; }
@Test public void testContinuation() throws Exception { assertEquals(underTest, underTest.getContinuationTrigger()); }
public List<DataRecord> merge(final List<DataRecord> dataRecords) { Map<DataRecord.Key, DataRecord> result = new HashMap<>(); dataRecords.forEach(each -> { if (PipelineSQLOperationType.INSERT == each.getType()) { mergeInsert(each, result); } else if (PipelineSQLOp...
@Test void assertUpdatePrimaryKeyBeforeDelete() { DataRecord beforeDataRecord = mockUpdateDataRecord(1, 2, 10, 50); DataRecord afterDataRecord = mockDeleteDataRecord(2, 10, 50); Collection<DataRecord> actual = groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRecord)); asser...
static Props loadPropsFromCommandLineArgs(String[] args) { if (args.length != 1) { throw new IllegalArgumentException("Only a single command-line argument is accepted " + "(absolute path to configuration file)"); } File propertyFile = new File(args[0]); Properties properties = new Propert...
@Test public void loadPropsFromCommandLineArgs_load_properties_from_file() throws Exception { File propsFile = temp.newFile(); FileUtils.write(propsFile, "foo=bar", StandardCharsets.UTF_8); Props result = ConfigurationUtils.loadPropsFromCommandLineArgs(new String[] {propsFile.getAbsolutePath()}); ass...
void close() throws Exception { destination.close(); mbus.destroy(); }
@Test public void requireThatDynamicThrottlingIsDefault() throws Exception { TestDriver driver = new TestDriver(new FeederParams(), "", null); assertEquals(DynamicThrottlePolicy.class, getThrottlePolicy(driver).getClass()); assertTrue(driver.close()); }
@Override public boolean supportsCatalogsInPrivilegeDefinitions() { return false; }
@Test void assertSupportsCatalogsInPrivilegeDefinitions() { assertFalse(metaData.supportsCatalogsInPrivilegeDefinitions()); }
@Override public Stream<FileSlice> getAllFileSlices(String partitionPath) { return execute(partitionPath, preferredView::getAllFileSlices, (path) -> getSecondaryView().getAllFileSlices(path)); }
@Test public void testGetAllFileSlices() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; when(primary.getAllFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getAllFileSlices(partitionPath); assertEquals...
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 shouldParseBigIntegerAsDecimalWithZeroScale() { BigInteger value = BigInteger.valueOf(Long.MAX_VALUE).add(new BigInteger("1")); SchemaAndValue schemaAndValue = Values.parseString( String.valueOf(value) ); assertEquals(Decimal.schema(0), schemaAndValue.sc...
public void syncTableMeta(String dbName, String tableName, boolean forceDeleteData) throws DdlException { Database db = GlobalStateMgr.getCurrentState().getDb(dbName); if (db == null) { throw new DdlException(String.format("db %s does not exist.", dbName)); } Table table = d...
@Test public void testSyncTableMetaTableNotExist() throws Exception { new MockUp<GlobalStateMgr>() { @Mock public Database getDb(String dbName) { return new Database(100, dbName); } }; new MockUp<Database>() { @Mock ...
@Override void toHtml() throws IOException { writeBackLink(); writeln("<br/>"); if (dependencies.isEmpty()) { writeln("#Aucune_dependance#"); return; } writeTitle("beans.png", getString("Dependencies")); final HtmlTable table = new HtmlTable(); table.beginTable(getString("Dependencies")); // tab...
@Test public void testDependencies() throws IOException { final ServletContext context = createNiceMock(ServletContext.class); final String javamelodyDir = "/META-INF/maven/net.bull.javamelody/"; final String webapp = javamelodyDir + "javamelody-test-webapp/"; expect(context.getResourcePaths("/META-INF/maven/"...
public static Node build(final List<JoinInfo> joins) { Node root = null; for (final JoinInfo join : joins) { if (root == null) { root = new Leaf(join.getLeftSource()); } if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) { throw new K...
@Test public void shouldComputeViableKeysWithoutOverlap() { // Given: when(j1.getLeftSource()).thenReturn(a); when(j1.getRightSource()).thenReturn(b); when(j2.getLeftSource()).thenReturn(a); when(j2.getRightSource()).thenReturn(c); when(j1.getLeftJoinExpression()).thenReturn(col1); when(j...
public static int rand(int min, int max) { return RANDOM.nextInt(max) % (max - min + 1) + min; }
@Test public void testRand() { Assert.assertEquals(8, StringKit.rand(8).length()); Assert.assertEquals(10, StringKit.rand(10).length()); for (int i = 0; i < 100; i++) { int num = StringKit.rand(1, 10); Assert.assertTrue(num < 11); Assert.assertTrue(num > ...
@Override void toHtml() throws IOException { writeHtmlHeader(); htmlCoreReport.toHtml(); writeHtmlFooter(); }
@Test public void testDoubleJavaInformations() throws IOException { final List<JavaInformations> myJavaInformationsList = List .of(new JavaInformations(null, true), new JavaInformations(null, true)); final HtmlReport htmlReport = new HtmlReport(collector, null, myJavaInformationsList, Period.TOUT, writer);...
@Override public DelayMeasurementStatCurrent getDmCurrentStat(MdId mdName, MaIdShort maName, MepId mepId, SoamId dmId) throws CfmConfigException, SoamConfigException { MepEntry mep = cfmMepService.getMep(mdName, maName, mepId); if (mep == null || mep.deviceId() == nul...
@Test public void testGetDmCurrentStat() throws CfmConfigException, SoamConfigException { expect(deviceService.getDevice(DEVICE_ID1)).andReturn(device1).anyTimes(); replay(deviceService); expect(mepService.getMep(MDNAME1, MANAME1, MEPID1)).andReturn(mep1).anyTimes(); replay(mepServi...
BrokerControlStates calculateNextBrokerState(int brokerId, BrokerHeartbeatRequestData request, long registerBrokerRecordOffset, Supplier<Boolean> hasLeaderships) { B...
@Test public void testCalculateNextBrokerState() { BrokerHeartbeatManager manager = newBrokerHeartbeatManager(); for (int brokerId = 0; brokerId < 6; brokerId++) { manager.register(brokerId, true); } manager.touch(0, true, 100); manager.touch(1, false, 98); ...
protected void commitTransaction(final Map<TopicPartition, OffsetAndMetadata> offsets, final ConsumerGroupMetadata consumerGroupMetadata) { if (!eosEnabled()) { throw new IllegalStateException(formatException("Exactly-once is not enabled")); } may...
@Test public void shouldThrowStreamsExceptionOnEosSendOffsetError() { eosAlphaMockProducer.sendOffsetsToTransactionException = new KafkaException("KABOOM!"); final StreamsException thrown = assertThrows( StreamsException.class, // we pass in `null` to verify that `sendOffset...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> objects = new AttributedList<>(); Marker marker = new Marker(null, null); final String containerId = fileid....
@Test public void testListFileNameDotDot() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new B2DirectoryFeature(session, fileid).mkdir( new Path(String.format("test-%s", new AsciiRandomStringService().random()), EnumSet.of...
@Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; }
@Test public void testIfSpringEmbeddedCacheManagerFactoryBeanCreatesACacheManagerEvenIfNoDefaultConfigurationLocationHasBeenSet() throws Exception { objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().build(); final SpringEmbeddedCacheManager springEmbed...
public static String hashSecretContent(Secret secret) { if (secret == null) { throw new RuntimeException("Secret not found"); } if (secret.getData() == null || secret.getData().isEmpty()) { throw new RuntimeException("Empty secret"); } St...
@Test public void testHashSecretContent() { Secret secret = new SecretBuilder() .addToData(Map.of("username", "foo")) .addToData(Map.of("password", "changeit")) .build(); assertThat(ReconcilerUtils.hashSecretContent(secret), is("756937ae")); }
public static CoordinatorRecord newConsumerGroupMemberSubscriptionTombstoneRecord( String groupId, String memberId ) { return new CoordinatorRecord( new ApiMessageAndVersion( new ConsumerGroupMemberMetadataKey() .setGroupId(groupId) ...
@Test public void testNewConsumerGroupMemberSubscriptionTombstoneRecord() { CoordinatorRecord expectedRecord = new CoordinatorRecord( new ApiMessageAndVersion( new ConsumerGroupMemberMetadataKey() .setGroupId("group-id") .setMemberId("membe...
public static String replaceAll(String s, final String what, final String withWhat) { StringBuilder sb = null; int fromIndex = 0; //index of last found '$' char + 1 boolean found = false; int length = s.length(); do { final int index = s.indexOf(what, fromIndex); found = index ...
@Test public void testEscaping() { assertEquals(Escaper.replaceAll("", "$", "$$"), ""); assertEquals(Escaper.replaceAll("$", "$", "$$"), "$$"); assertEquals(Escaper.replaceAll(" $", "$", "$$"), " $$"); assertEquals(Escaper.replaceAll(" $ ", "$", "$$"), " $$ "); assertEquals(Escaper.replaceAll(" ...
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) { this.jsonPath = jsonPath; this.resultMatcher = resultMatcher; }
@Test public void shouldNotMatchOnInvalidJson() { ReadContext invalidJson = JsonPath.parse("invalid-json"); assertThat(invalidJson, not(withJsonPath("$.expensive", equalTo(10)))); }
@Override public Processor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>> get() { return new ContextualProcessor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>>() { private TimestampedKeyValu...
@Test public void shouldDeleteKeyNoPropagateV0() { final StoreBuilder<TimestampedKeyValueStore<Bytes, SubscriptionWrapper<String>>> storeBuilder = storeBuilder(); final SubscriptionReceiveProcessorSupplier<String, String> supplier = supplier(storeBuilder); final Processor<String, ...
public String getType() { return type; }
@Test public void getType() { JobScheduleParam jobScheduleParam = mock( JobScheduleParam.class ); when( jobScheduleParam.getType() ).thenCallRealMethod(); String type = "hitachi"; ReflectionTestUtils.setField( jobScheduleParam, "type", type ); Assert.assertEquals( type, jobScheduleParam.getType() ...
public static boolean isUnanimousCandidate( final ClusterMember[] clusterMembers, final ClusterMember candidate, final int gracefulClosedLeaderId) { int possibleVotes = 0; for (final ClusterMember member : clusterMembers) { if (member.id == gracefulClosedLeaderId) ...
@Test void isUnanimousCandidateReturnFalseIfLeaderClosesGracefully() { final int gracefulClosedLeaderId = 1; final ClusterMember candidate = newMember(2, 2, 100); final ClusterMember[] members = new ClusterMember[] { newMember(1, 2, 100), newMember(2, 2, 1...
public static <T> @Nullable String getClassNameOrNull(@Nullable T value) { if (value != null) { return value.getClass().getName(); } return null; }
@Test public void testGetClassNameOrNullNull() { assertNull(SingleStoreUtil.getClassNameOrNull(null)); }
public <KEY> Where<KEY> where(KeySelector<T1, KEY> keySelector) { requireNonNull(keySelector); final TypeInformation<KEY> keyType = TypeExtractor.getKeySelectorTypes(keySelector, input1.getType()); return where(keySelector, keyType); }
@Test void testSetAllowedLateness() { Duration lateness = Duration.ofMillis(42L); JoinedStreams.WithWindow<String, String, String, TimeWindow> withLateness = dataStream1 .join(dataStream2) .where(keySelector) .e...
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds); intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub); for (String feature : FEATURES_IN_ORDER) { ...
@Test void testApplyTransforms_blwf() { // given List<Integer> glyphsAfterGsub = Arrays.asList(602,336,516); // when List<Integer> result = gsubWorkerForDevanagari.applyTransforms(getGlyphIds("ह्रट्र")); // then assertEquals(glyphsAfterGsub, result); }
public static Boolean jqBoolean(String value, String expression) { return H2Functions.jq(value, expression, JsonNode::asBoolean); }
@Test public void jqBoolean() { Boolean jqString = H2Functions.jqBoolean("{\"a\": true}", ".a"); assertThat(jqString, is(true)); }
public static ReceiptHandle decode(String receiptHandle) { List<String> dataList = Arrays.asList(receiptHandle.split(SEPARATOR)); if (dataList.size() < 8) { throw new IllegalArgumentException("Parse failed, dataList size " + dataList.size()); } long startOffset = Long.parseLo...
@Test(expected = IllegalArgumentException.class) public void testDecodeWithInvalidString() { String invalidReceiptHandle = "invalid_data"; ReceiptHandle.decode(invalidReceiptHandle); }
public static String convertToString(Object parsedValue, Type type) { if (parsedValue == null) { return null; } if (type == null) { return parsedValue.toString(); } switch (type) { case BOOLEAN: case SHORT: case INT: ...
@Test public void testConvertValueToStringShort() { assertEquals("32767", ConfigDef.convertToString(Short.MAX_VALUE, Type.SHORT)); assertNull(ConfigDef.convertToString(null, Type.SHORT)); }
@Override public void d(String tag, String message, Object... args) { }
@Test public void debugNotLogged() { String expectedTag = "TestTag"; logger.d(expectedTag, "Hello %s", "World"); assertNotLogged(); }
public Map<String, String> getCharacteristics() { return characteristics; }
@Test public void setCharacteristics_null_is_considered_as_empty() { CeTask task = underTest.setType("TYPE_1").setUuid("UUID_1") .setCharacteristics(null) .build(); assertThat(task.getCharacteristics()).isEmpty(); }
public static Configuration configurePythonDependencies(ReadableConfig config) { final PythonDependencyManager pythonDependencyManager = new PythonDependencyManager(config); final Configuration pythonDependencyConfig = new Configuration(); pythonDependencyManager.applyToConfiguration(pythonDepen...
@Test void testPythonExecutables() { Configuration config = new Configuration(); config.set(PYTHON_EXECUTABLE, "venv/bin/python3"); config.set(PYTHON_CLIENT_EXECUTABLE, "python37"); Configuration actual = configurePythonDependencies(config); Configuration expectedConfigurati...
@Override public Cost multiplyBy(double factor) { if (isInfinite()) { return INFINITY; } return new Cost(rows * factor, cpu * factor, network * factor); }
@Test public void testMultiply() { CostFactory factory = CostFactory.INSTANCE; Cost originalCost = factory.makeCost(1.0d, 2.0d, 3.0d); Cost multipliedCost = factory.makeCost(3.0d, 6.0d, 9.0d); assertEquals(multipliedCost, originalCost.multiplyBy(3.0d)); Cost infiniteCost = ...
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldCreateUdfFactoryWithJarPathWhenExternal() { final UdfFactory tostring = FUNC_REG.getUdfFactory(FunctionName.of("tostring")); String expectedPath = String.join(File.separator, "src", "test", "resources", "udf-example.jar"); assertThat(tostring.getMetadata().getPath(), equalTo(expect...
@Override public void failover(NamedNode master) { connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName()); }
@Test public void testFailover() throws InterruptedException { Collection<RedisServer> masters = connection.masters(); connection.failover(masters.iterator().next()); Thread.sleep(10000); RedisServer newMaster = connection.masters().iterator().next(); assert...
public TimestampOffset entry(int n) { return maybeLock(lock, () -> { if (n >= entries()) throw new IllegalArgumentException("Attempt to fetch the " + n + "th entry from time index " + file().getAbsolutePath() + " which has size " + entries()); return p...
@Test public void testEntryOverflow() { assertThrows(IllegalArgumentException.class, () -> idx.entry(0)); }
@Override public void triggerAfterCompletion(GlobalTransaction tx) { if (tx.getGlobalTransactionRole() == GlobalTransactionRole.Launcher) { for (TransactionHook hook : getCurrentHooks()) { try { hook.afterCompletion(); } catch (Exception e) { ...
@Test public void testTriggerAfterCompletion() { MockedStatic<TransactionHookManager> enhancedTransactionHookManager = Mockito.mockStatic(TransactionHookManager.class); enhancedTransactionHookManager.when(TransactionHookManager::getHooks).thenReturn(Collections.singletonList(new MockTransactionHook(...
public String generateError(String error) { Map<String, String> values = ImmutableMap.of( PARAMETER_TOTAL_WIDTH, valueOf(MARGIN + computeWidth(error) + MARGIN), PARAMETER_LABEL, error); StringSubstitutor strSubstitutor = new StringSubstitutor(values); return strSubstitutor.replace(errorTemplate)...
@Test public void fail_when_unknown_character() { initSvgGenerator(); assertThatThrownBy(() -> underTest.generateError("Méssage with accent")) .hasMessage("Invalid character 'é'"); }
public ImmutableSet<String> loadAllMessageStreams(final StreamPermissions streamPermissions) { return allStreamsProvider.get() // Unless explicitly queried, exclude event and failure indices by default // Having these indices in every search, makes sorting almost impossible ...
@Test public void findsStreams() { final PermittedStreams sut = new PermittedStreams(() -> java.util.stream.Stream.of("oans", "zwoa", "gsuffa")); ImmutableSet<String> result = sut.loadAllMessageStreams(id -> true); assertThat(result).containsExactlyInAnyOrder("oans", "zwoa", "gsuffa"); }
public static <T> MeshRuleCache<T> build( String protocolServiceKey, BitList<Invoker<T>> invokers, Map<String, VsDestinationGroup> vsDestinationGroupMap) { if (CollectionUtils.isNotEmptyMap(vsDestinationGroupMap)) { BitList<Invoker<T>> unmatchedInvokers = new BitL...
@Test void testBuild() { BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); Subset subset = new Subset(); subset.setName("TestSubset"); DestinationRule destinationRule = new Destinatio...
@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 testNormalPublishConfigNotCas() throws Exception { String dataId = "testNormalPublishConfigNotCas"; String group = "group"; String tenant = "tenant"; String content = "content"; ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); ...
public static String padStart(String str, int targetLength, char padString) { while (str.length() < targetLength) { str = padString + str; } return str; }
@Test public void padStart_Test() { String binaryString = "010011"; String expected = "00010011"; Assertions.assertEquals(expected, TbUtils.padStart(binaryString, 8, '0')); binaryString = "1001010011"; expected = "1001010011"; Assertions.assertEquals(expected, TbUtils...
@Override public void execute(final ChannelHandlerContext context, final Object message, final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine, final ConnectionSession connectionSession) { ExecutorService executorService = determineSuitableExecutorService(connectionSession); context.ch...
@Test void assertExecuteWithDistributedTransaction() { ContextManager contextManager = mockContextManager(); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); ConnectionSession connectionSession = mock(ConnectionSession.class, RETURNS_DEEP_STUBS); when(...