focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Optional<String> reasonAllControllersZkMigrationNotReady( MetadataVersion metadataVersion, Map<Integer, ControllerRegistration> controllers ) { if (!metadataVersion.isMigrationSupported()) { return Optional.of("The metadata.version too low at " + metadataVersion); ...
@Test public void testZkMigrationReadyIfControllerRegistrationNotSupported() { assertEquals(Optional.empty(), QUORUM_FEATURES.reasonAllControllersZkMigrationNotReady( MetadataVersion.IBP_3_4_IV0, Collections.emptyMap())); }
@Override public boolean needAnnounceBacklog() { return initialCredit == 0 && numCreditsAvailable == 0; }
@Test void testNeedAnnounceBacklog() throws Exception { int numCredits = 2; CreditBasedSequenceNumberingViewReader reader1 = createNetworkSequenceViewReader(numCredits); assertThat(reader1.needAnnounceBacklog()).isFalse(); reader1.addCredit(-numCredits); asse...
@Override public long readLong() throws EOFException { if (availableLong() < 8) { throw new EOFException(); } long result = _dataBuffer.getLong(_currentOffset); _currentOffset += 8; return result; }
@Test void testReadLong() throws EOFException { long read = _dataBufferPinotInputStream.readLong(); assertEquals(read, _byteBuffer.getLong(0)); assertEquals(_dataBufferPinotInputStream.getCurrentOffset(), Long.BYTES); }
public static Boolean judge(final ConditionData conditionData, final String realData) { if (Objects.isNull(conditionData) || StringUtils.isBlank(conditionData.getOperator())) { return false; } PredicateJudge predicateJudge = newInstance(conditionData.getOperator()); if (!(pre...
@Test public void testMatchJudge() { conditionData.setOperator(OperatorEnum.MATCH.getAlias()); conditionData.setParamValue("/http/**"); assertTrue(PredicateJudgeFactory.judge(conditionData, "/http/**")); assertTrue(PredicateJudgeFactory.judge(conditionData, "/http/test")); as...
public Long getTime() { return time; }
@Test public void testDefaultTime() { SplunkHECConfiguration config = new SplunkHECConfiguration(); assertNull(config.getTime()); }
public MapWritable() { super(); this.instance = new HashMap<Writable, Writable>(); }
@SuppressWarnings("unchecked") @Test public void testMapWritable() { Text[] keys = { new Text("key1"), new Text("key2"), new Text("Key3"), }; BytesWritable[] values = { new BytesWritable("value1".getBytes()), new BytesWritable("value2".getBytes()), ne...
public static String getLocalIp(String... preferredNetworks) { InetAddress address = getLocalAddress(preferredNetworks); if (null != address) { String hostAddress = address.getHostAddress(); if (address instanceof Inet6Address) { if (hostAddress.contains("%")) { ...
@Test public void testGetLocalIp() { assertThat(NetUtil.getLocalIp()).isNotNull(); }
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldFailValidation_WhenSameMaterialUsedBy2ConfigRepos() { assertThatThrownBy(() -> xmlLoader.loadConfigHolder(configWithConfigRepos( """ <config-repos> <config-repo pluginId="myplugin" id="id1"> ...
public boolean equals(@NonNull String id1, @NonNull String id2) { return compare(id1, id2) == 0; }
@Test public void testEqualsCaseSensitiveEmailAddress() { IdStrategy idStrategy = new IdStrategy.CaseSensitiveEmailAddress(); assertFalse(idStrategy.equals("john.smith@acme.org", "John.Smith@acme.org")); assertFalse(idStrategy.equals("john.smith@acme.org", "John.Smith@ACME.org")); as...
public static List<MetricsPacket.Builder> toMetricsPackets(String jsonString) { List<MetricsPacket.Builder> packets = new ArrayList<>(); var mapper = objectMapper(); try (JsonParser jp = mapper.createParser(jsonString)) { while (jp.nextToken() != null) { YamasJsonMode...
@Test public void empty_json_string_yields_empty_packet_list() { List<MetricsPacket.Builder> builders = toMetricsPackets(""); assertTrue(builders.isEmpty()); }
@Override public void fetchSegmentToLocal(URI downloadURI, File dest) throws Exception { // Create a RoundRobinURIProvider to round robin IP addresses when retry uploading. Otherwise may always try to // download from a same broken host as: 1) DNS may not RR the IP addresses 2) OS cache the DNS resoluti...
@Test(expectedExceptions = AttemptsExceededException.class) public void testFetchSegmentToLocalAllDownloadAttemptsFailed() throws Exception { FileUploadDownloadClient client = mock(FileUploadDownloadClient.class); // All attempts failed when(client.downloadFile(any(), any(), any())).thenReturn(300);...
@Override public SerializerAdapter serializerFor(Object object, boolean includeSchema) { Class<?> clazz = object == null ? null : object.getClass(); SerializerAdapter serializer = null; if (clazz != null) { serializer = serializersByClass.get(clazz); } if (serial...
@Test public void when_doesNotFind_then_Delegates() { // Given DelegatingSerializationService service = new DelegatingSerializationService(emptyMap(), DELEGATE); // When // Then assertThat(service.serializerFor(TYPE_ID).getImpl()).isInstanceOf(ValueSerializer.class); ...
@Override public void doPush(String clientId, Subscriber subscriber, PushDataWrapper data) { pushService.pushDataWithoutCallback(subscriber, handleClusterData(replaceServiceInfoName(data, subscriber), subscriber)); }
@Test void testDoPush() { pushExecutor.doPush(rpcClientId, subscriber, pushData); verify(pushService).pushDataWithoutCallback(eq(subscriber), any(ServiceInfo.class)); }
public static String describe(List<org.apache.iceberg.expressions.Expression> exprs) { return exprs.stream().map(Spark3Util::describe).collect(Collectors.joining(", ")); }
@Test public void testDescribeSortOrder() { Schema schema = new Schema( required(1, "data", Types.StringType.get()), required(2, "time", Types.TimestampType.withoutZone())); assertThat(Spark3Util.describe(buildSortOrder("Identity", schema, 1))) .as("Sort order isn't co...
@Nullable @SuppressWarnings("checkstyle:returncount") static Metadata resolve(InternalSerializationService ss, Object target, boolean key) { try { if (target instanceof Data) { Data data = (Data) target; if (data.isPortable()) { ClassDefini...
@Test public void test_java() { InternalSerializationService ss = new DefaultSerializationServiceBuilder().build(); Metadata metadata = SampleMetadataResolver.resolve(ss, new Value(), key); assertThat(metadata.options()).containsExactly( entry(key ? OPTION_KEY_FORMAT : OPTIO...
@Override public final int hashCode() { return delegate.hashCode(); }
@Test public void requireThatHashCodeIsImplemented() { assertEquals(newLazySet(null).hashCode(), newLazySet(null).hashCode()); }
@Override public String format(final Schema schema) { final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema); return options.contains(Option.AS_COLUMN_LIST) ? stripTopLevelStruct(converted) : converted; }
@Test public void shouldEscapeReservedWords() { // Given: final Schema structSchema = SchemaBuilder.struct() .field("COL1", Schema.STRING_SCHEMA) .field("COL2", SchemaBuilder .struct() .field("COL3", Schema.STRING_SCHEMA) .build()) .build(); fin...
public int getSize() { return size; }
@Test public void testArraySizeConstructor() { ByteArrayHashIndex obj = new ByteArrayHashIndex( new RowMeta(), 1 ); assertEquals( 1, obj.getSize() ); obj = new ByteArrayHashIndex( new RowMeta(), 2 ); assertEquals( 2, obj.getSize() ); obj = new ByteArrayHashIndex( new RowMeta(), 3 ); assertEq...
@Override public List<RemoteInstance> queryRemoteNodes() { List<RemoteInstance> remoteInstances = new ArrayList<>(20); try { List<ServiceInstance<RemoteInstance>> serviceInstances = serviceCache.getInstances(); serviceInstances.forEach(serviceInstance -> { Rem...
@Test public void queryRemoteNodes() { }
public int getHealth(int wizard) { return wizards[wizard].getHealth(); }
@Test void testGetHealth() { var wizardNumber = 0; var bytecode = new int[8]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); bytecode[3] = 50; // health amount bytecode[4] = SET_HEALTH.getIntValue(); bytecode...
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_skip_missing_location_strings() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n" + " When second step\n" + ...
public boolean isUnresolved() { return inetSocketAddress.isUnresolved(); }
@Test public void testIsUnresolved() throws Exception { final InetSocketAddress inetSocketAddress = new InetSocketAddress(Inet4Address.getLoopbackAddress(), 12345); final ResolvableInetSocketAddress address = new ResolvableInetSocketAddress(inetSocketAddress); assertThat(address.isUnresolve...
@Override public Path find() throws BackgroundException { return this.find(Context.files); }
@Test public void testFindWithUsername() throws Exception { final NextcloudHomeFeature feature = new NextcloudHomeFeature(new Host(new NextcloudProtocol(), new Credentials("u"))); assertEquals(new Path("/ocs/v1.php", EnumSet.of(Path.Type.directory)), feature.find(NextcloudHomeFeature.Context.ocs)); ...
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException { final List<MavenArtifact> result = new ArrayList<>(); try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); JsonParser ...
@Test public void shouldProcessCorrectlyArtifactoryAnswerMisMatchSha256() throws IOException { // Given Dependency dependency = new Dependency(); dependency.setSha1sum("c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0f"); dependency.setSha256sum("512b4bf6927f4864acc419b8c5109c23361c30ed1f5798...
@VisibleForTesting protected int compactionTaskLimit() { if (Config.lake_compaction_max_tasks >= 0) { return Config.lake_compaction_max_tasks; } WarehouseManager manager = GlobalStateMgr.getCurrentState().getWarehouseMgr(); Warehouse warehouse = manager.getCompactionWareh...
@Test public void testCompactionTaskLimit() { CompactionScheduler compactionScheduler = new CompactionScheduler(null, null, null, null, ""); int defaultValue = Config.lake_compaction_max_tasks; // explicitly set config to a value bigger than default -1 Config.lake_compaction_max_tas...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultPatchDescription) { final DefaultPatchDescription that = (DefaultPatchDescription) obj; return this.getClass() == that.getClass() && ...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(defaultPatchDescription1, sameAsDefaultPatchDescription1) .addEqualityGroup(defaultPatchDescription2) .addEqualityGroup(defaultPatchDescription3) .addEqualityGroup(defaultPat...
boolean convertDeviceProfileForVersion330(JsonNode profileData) { boolean isUpdated = false; if (profileData.has("alarms") && !profileData.get("alarms").isNull()) { JsonNode alarms = profileData.get("alarms"); for (JsonNode alarm : alarms) { if (alarm.has("createR...
@Test void convertDeviceProfileAlarmRulesForVersion330AlarmNodeNull() throws JsonProcessingException { JsonNode spec = JacksonUtil.toJsonNode("{ \"alarms\" : null }"); JsonNode expected = JacksonUtil.toJsonNode("{ \"alarms\" : null }"); assertThat(service.convertDeviceProfileForVersion330(s...
public String getName() { return name; }
@Test public void testBooleanAssumption() { GoldFish goldFish = new GoldFish("Windows Jelly", 1); assumeTrue(System.getProperty("os.name").contains("Windows")); assertThat(goldFish.getName(), equalToIgnoringCase("Windows Jelly")); }
public static String getRemoteIp(HttpServletRequest request) { String remoteIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getSourceIp(); if (StringUtils.isBlank(remoteIp)) { remoteIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getR...
@Test void testGetRemoteIpFromRequest() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); assertEquals("127.0.0.1", RequestUtil.getRemoteIp(request)); Mockito.when(request.getHeader(...
@Override public boolean isEmpty() { return topicNames.isEmpty(); }
@Test public void testIsEmpty() { Set<String> topicNames = Collections.emptySet(); Set<Uuid> topicIds = new TopicIds(topicNames, TopicsImage.EMPTY); assertEquals(topicNames.size(), topicIds.size()); }
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseWindows10WithChromeTest() { final String uaStr = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"; final UserAgent ua = UserAgentUtil.parse(uaStr); assertEquals("Chrome", ua.getBrowser().toString()); assertEquals("70.0....
static CounterResult fromJson(String json) { return JsonUtil.parse(json, CounterResultParser::fromJson); }
@Test public void missingFields() { assertThatThrownBy(() -> CounterResultParser.fromJson("{}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing string: unit"); assertThatThrownBy(() -> CounterResultParser.fromJson("{\"unit\":\"bytes\"}")) .isInstanceOf...
public String orderClause(AmountRequest amountRequest) { return orderClause(amountRequest, ORDER_TERM_TO_SQL_STRING); }
@Test void mapWithSomeIllegalStuff1() { final AmountRequest pageRequest = new AmountRequest("createdAt:ASC,\"delete * from jobtable\"updatedAt:DESC", 2); assertThat(amountMapper.orderClause(pageRequest)).isEqualTo(" ORDER BY createdAt ASC"); }
public Set<TaskId> activeTasks() { return unmodifiableSet(assignedActiveTasks.taskIds()); }
@Test public void shouldNotModifyActiveView() { final ClientState clientState = new ClientState(1); final Set<TaskId> taskIds = clientState.activeTasks(); assertThrows(UnsupportedOperationException.class, () -> taskIds.add(TASK_0_0)); assertThat(clientState, hasActiveTasks(0)); }
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest req) { var certs = req.getClientCertificateChain(); log.fine(() -> "Certificate chain contains %d elements".formatted(certs.size())); if (certs.isEmpty()) { log.fine("Missing client certificate"); re...
@Test void fails_on_missing_certificate_in_legacy_mode() { var req = FilterTestUtils.newRequestBuilder().build(); var responseHandler = new MockResponseHandler(); newFilterWithLegacyMode().filter(req, responseHandler); assertNotNull(responseHandler.getResponse()); assertEqual...
@Override public void configure(Map<String, ?> props) { final SimpleConfig config = new SimpleConfig(CONFIG_DEF, props); casts = parseFieldTypes(config.getList(SPEC_CONFIG)); wholeValueCastType = casts.get(WHOLE_VALUE_CAST); schemaUpdateCache = new SynchronizedCache<>(new LRUCache<>(...
@Test public void testConfigInvalidSchemaType() { assertThrows(ConfigException.class, () -> xformKey.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:faketype"))); }
@Override public boolean isOff(Ability ability) { return false; }
@Test public void claimsEveryAbilityIsOn() { Ability random = DefaultBot.getDefaultBuilder() .name("randomsomethingrandom").build(); toggle = new DefaultToggle(); defaultBot = new DefaultBot(null, EMPTY, db, toggle); defaultBot.onRegister(); assertFalse(toggle.is...
@Override public CompletableFuture<RegistrationResponse> registerJobMaster( final JobMasterId jobMasterId, final ResourceID jobManagerResourceId, final String jobManagerAddress, final JobID jobId, final Time timeout) { checkNotNull(jobMasterId); ...
@Test void testJobMasterBecomesUnreachableTriggersDisconnect() throws Exception { final JobID jobId = new JobID(); final ResourceID jobMasterResourceId = ResourceID.generate(); final CompletableFuture<ResourceManagerId> disconnectFuture = new CompletableFuture<>(); final TestingJobMa...
@Override public Map<String, Object> unbox() { if (val == null) { return null; } Map<String, Object> ret = new HashMap<>(); for (Map.Entry<SelString, SelType> entry : val.entrySet()) { switch (entry.getValue().type()) { case STRING: case LONG: case DOUBLE: c...
@Test public void testUnbox() { Map<String, Object> map = orig.unbox(); assertEquals("{foo=bar, num=123}", String.valueOf(map)); }
@Override public Optional<String> resolveQueryFailure(QueryStats controlQueryStats, QueryException queryException, Optional<QueryObjectBundle> test) { return mapMatchingPrestoException(queryException, CONTROL_CHECKSUM, ImmutableSet.of(COMPILER_ERROR, GENERATED_BYTECODE_TOO_LARGE), e -> O...
@Test public void testResolveCompilerError() { assertEquals( getFailureResolver().resolveQueryFailure( CONTROL_QUERY_STATS, new PrestoQueryException( new RuntimeException(), fa...
@VisibleForTesting OutputBufferMemoryManager getMemoryManager() { return memoryManager; }
@Test public void testSharedBufferBlocking() { SettableFuture<?> blockedFuture = SettableFuture.create(); MockMemoryReservationHandler reservationHandler = new MockMemoryReservationHandler(blockedFuture); AggregatedMemoryContext memoryContext = newRootAggregatedMemoryContext(reservationH...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final P4MeterModel other = (P4MeterModel) obj; return Objects.equals(this.id, other.id) ...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(P4_METER_MODEL_1, SAME_AS_P4_METER_MODEL_1) .addEqualityGroup(P4_METER_MODEL_2) .addEqualityGroup(P4_METER_MODEL_3) .testEquals(); }
public boolean createDataConnection(DataConnectionCatalogEntry dl, boolean replace, boolean ifNotExists) { if (replace) { dataConnectionStorage.put(dl.name(), dl); listeners.forEach(TableListener::onTableChanged); return true; } else { boolean added = data...
@Test public void when_createsDuplicateDataConnection_then_throws() { // given DataConnectionCatalogEntry dataConnectionCatalogEntry = dataConnection(); given(relationsStorage.putIfAbsent(eq(dataConnectionCatalogEntry.name()), isA(DataConnectionCatalogEntry.class))).willReturn(false); ...
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testPrimitiveIntegerFromJsonOptions() throws Exception { String optionsJson = "{\"options\":{\"appName\":\"ProxyInvocationHandlerTest\",\"optionsId\":1,\"int\":\"100\"},\"display_data\":[{\"namespace\":\"org.apache.beam.sdk.options.ProxyInvocationHandlerTest$DisplayDataOptions\",\"key\":...
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { var requestIdGenerator = platform.getContainer().getOptionalComponentByType(RequestIdGenerator.class); if (requestIdGenerator.isEmpty()) { chain.doFilter(request, r...
@Test public void filter_put_id_in_MDC_and_remove_it_after_chain_throws_exception() throws IOException, ServletException { RuntimeException exception = new RuntimeException("Simulating chain failing"); String requestId = "request id"; when(requestIdGenerator.generate()).thenReturn(requestId); doAnswer...
public boolean canRunAppAM(Resource amResource) { if (Math.abs(maxAMShare - -1.0f) < 0.0001) { return true; } Resource maxAMResource = computeMaxAMResource(); getMetrics().setMaxAMShare(maxAMResource); Resource ifRunAMResource = Resources.add(amResourceUsage, amResource); return Resources...
@Test public void testCanRunAppAMReturnsTrue() { conf.set(YarnConfiguration.RESOURCE_TYPES, CUSTOM_RESOURCE); ResourceUtils.resetResourceTypes(conf); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); Resource maxS...
@SuppressWarnings("unchecked") public static void validateFormat(Object offsetData) { if (offsetData == null) return; if (!(offsetData instanceof Map)) throw new DataException("Offsets must be specified as a Map"); validateFormat((Map<Object, Object>) offsetData); ...
@Test public void testValidateFormatMapWithNonPrimitiveKeys() { Map<Object, Object> offsetData = Collections.singletonMap("key", new Object()); DataException e = assertThrows(DataException.class, () -> OffsetUtils.validateFormat(offsetData)); assertThat(e.getMessage(), containsString("Offset...
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 poolReSubscribesAndReadsManyEvents() throws Exception { kinesis = new EFOStubbedKinesisAsyncClient(1); kinesis.stubSubscribeToShard("shard-000", eventsWithRecords(18, 300)); kinesis.stubSubscribeToShard("shard-000", eventsWithoutRecords(318, 3)); kinesis.stubSubscribeToShard("shard-...
@Override public void start() { try { createAndStartGrpcServer(); } catch (final IOException e) { throw new IllegalStateException("Failed to start the grpc server", e); } }
@Test void testGracefulShutdown() { // The server takes 2s seconds to shutdown final TestServer server = new TestServer(2000); when(this.factory.createServer()).thenReturn(server); // And we give it 5s to shutdown final GrpcServerLifecycle lifecycle = new Gr...
@Override public RowData nextRecord(RowData reuse) { // return the next row row.setRowId(this.nextRow++); return row; }
@Test void testReadFileWithTypes(@TempDir File folder) throws IOException { String file = new File(folder, "testOrc").getPath(); int rowSize = 1024; prepareReadFileWithTypes(file, rowSize); // second test read. FileInputSplit split = createSplits(new Path(file), 1)[0]; ...
@Override public double getMean() { if (values.length == 0) { return 0; } double sum = 0; for (long value : values) { sum += value; } return sum / values.length; }
@Test public void calculatesAMeanOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); assertThat(emptySnapshot.getMean()) .isZero(); }
static void filterProperties(Message message, Set<String> namesToClear) { List<Object> retainedProperties = messagePropertiesBuffer(); try { filterProperties(message, namesToClear, retainedProperties); } finally { retainedProperties.clear(); // ensure no object references are held due to any exc...
@Test void filterProperties_message_handlesOnSetException() throws JMSException { Message message = mock(Message.class); when(message.getPropertyNames()).thenReturn( Collections.enumeration(Collections.singletonList("JMS_SQS_DeduplicationId"))); when(message.getObjectProperty("JMS_SQS_DeduplicationId"...
public OpenConfigChannelHandler addConfig(OpenConfigConfigOfChannelHandler config) { modelObject.config(config.getModelObject()); return this; }
@Test public void testAddConfig() { // test Handler OpenConfigChannelHandler channel = new OpenConfigChannelHandler(1, parent); // call addConfig OpenConfigConfigOfChannelHandler configOfChannel = new OpenConfigConfigOfChannelHandler(channel); // expected ModelO...
@VisibleForTesting protected void flattenMap(GenericRow record, List<String> columns) { for (String column : columns) { Object value = record.getValue(column); if (value instanceof Map) { Map<String, Object> map = (Map) value; List<String> mapColumns = new ArrayList<>(); for (M...
@Test public void testFlattenMap() { ComplexTypeTransformer transformer = new ComplexTypeTransformer(new ArrayList<>(), "."); // test flatten root-level tuples GenericRow genericRow = new GenericRow(); genericRow.putValue("a", 1L); Map<String, Object> map1 = new HashMap<>(); genericRow.putVal...
@Override public Object toConnectRow(final Object ksqlData) { if (!(ksqlData instanceof Struct)) { return ksqlData; } final Schema schema = getSchema(); final Struct struct = new Struct(schema); Struct originalData = (Struct) ksqlData; Schema originalSchema = originalData.schema(); ...
@Test public void shouldTransformStructWithNestedStructs() { // Given: final Schema innerStructSchemaWithoutOptional = getInnerStructSchema(false); final Schema innerStructSchemaWithOptional = getInnerStructSchema(true); Struct innerInnerStructWithOptional = getNestedData(innerStructSchemaWithOptiona...
private <T> T newPlugin(Class<T> klass) { // KAFKA-8340: The thread classloader is used during static initialization and must be // set to the plugin's classloader during instantiation try (LoaderSwap loaderSwap = withClassLoader(klass.getClassLoader())) { return Utils.newInstance(kl...
@Test public void shouldThrowIfPluginMissingSuperclass() { assertThrows(ConnectException.class, () -> plugins.newPlugin( TestPlugin.BAD_PACKAGING_MISSING_SUPERCLASS.className(), new AbstractConfig(new ConfigDef(), Collections.emptyMap()), Converter.class ...
Flux<List<ServiceInstance>> doRouter(Flux<List<ServiceInstance>> allServers, PolarisRouterContext routerContext) { ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(allServers, instanceTransformer); List<ServiceInstance> filteredInstances = new ArrayList<>(); if (serviceInstances....
@Test public void testRouter() { when(polarisRuleBasedRouterProperties.isEnabled()).thenReturn(true); try (MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) { mockedApplicationContextAwareUtils.when(() -> ApplicationContextAw...
public static Object typeConvert(String tableName ,String columnName, String value, int sqlType, String mysqlType) { if (value == null || (value.equals("") && !(isText(mysqlType) || sqlType == Types.CHAR || sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR))) { return null; ...
@Test public void typeConvertInputNotNullNotNullNotNullNegativeNotNullOutputPositive() { // Arrange final String tableName = "foo"; final String columnName = "foo"; final String value = "1234"; final int sqlType = -5; final String mysqlType = "foo"; // Act final Object actual = ...
public static FactoryBuilder newFactoryBuilder(Propagation.Factory delegate) { return new FactoryBuilder(delegate); }
@Test void newFactory_noFields() { assertThat(BaggagePropagation.newFactoryBuilder(B3Propagation.FACTORY).build()) .isSameAs(B3Propagation.FACTORY); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "number", "cannot be null")); } return FEELFnResult.ofResult( number.abs() ); }
@Test void absFunctionNumber() { FunctionTestUtil.assertResult(absFunction.invoke(valueOf(10)), valueOf(10)); FunctionTestUtil.assertResult(absFunction.invoke(valueOf(-10)), valueOf(10)); FunctionTestUtil.assertResultError(absFunction.invoke((BigDecimal) null), InvalidParametersEvent.class);...
public List<MetadataLogEntry> previousFiles() { return previousFiles; }
@Test public void testJsonWithPreviousMetadataLog() throws Exception { long previousSnapshotId = System.currentTimeMillis() - new Random(1234).nextInt(3600); String manifestList = createManifestListWithManifestFile(previousSnapshotId, null, "file:/tmp/manifest1.avro"); Snapshot previousSnapshot =...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { if(!session.getClient().setFileType(FTP.BINARY_FILE_TYPE)) { throw new FTPException(session.getClient().getReplyCode(), session.ge...
@Test public void testDoubleCloseStream() throws Exception { final Path file = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new DefaultTouchFeature<>(new FTPWriteFeature(session)).touch(file, new TransferStatus()); final TransferS...
public String getActiveVersionNodePath() { return String.join("/", key, ACTIVE_VERSION); }
@Test void assertGetActiveVersionNodePath() { assertThat(new MetaDataVersion("foo", "0", "1").getActiveVersionNodePath(), is("foo/active_version")); }
String toLogMessage(TbMsg msg) { return "\n" + "Incoming message:\n" + msg.getData() + "\n" + "Incoming metadata:\n" + JacksonUtil.toString(msg.getMetaData().getData()); }
@Test void givenMsg_whenToLog_thenReturnString() { TbLogNode node = new TbLogNode(); String data = "{\"key\": \"value\"}"; TbMsgMetaData metaData = new TbMsgMetaData(Map.of("mdKey1", "mdValue1", "mdKey2", "23")); TbMsg msg = TbMsg.newMsg(TbMsgType.POST_TELEMETRY_REQUEST, TenantId.SYS...
public static <T> boolean isNullOrEmpty(Collection<T> collection) { if (collection == null) return true; return collection.isEmpty(); }
@Test void isNullOrEmptyIsTrueForEmptyArray() { assertThat(isNullOrEmpty(new String[]{})).isTrue(); }
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewKey(), "New name must not be null!"); byte[] k...
@Test public void testRename_keyNotExist() { testInClusterReactive(connection -> { Integer originalSlot = getSlotForKey(originalKey, (RedissonReactiveRedisClusterConnection) connection); newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot), connectio...
public static ExecutableStage forGrpcPortRead( QueryablePipeline pipeline, PipelineNode.PCollectionNode inputPCollection, Set<PipelineNode.PTransformNode> initialNodes) { checkArgument( !initialNodes.isEmpty(), "%s must contain at least one %s.", GreedyStageFuser.class.getS...
@Test public void userStateIncludedInStage() { Environment env = Environments.createDockerEnvironment("common"); PTransform readTransform = PTransform.newBuilder() .putInputs("input", "impulse.out") .putOutputs("output", "read.out") .setSpec( Functio...
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = false; boolean containsNull = false; // Spec. definiti...
@Test void invokeListParamNull() { FunctionTestUtil.assertResultError(anyFunction.invoke((List) null), InvalidParametersEvent.class); }
static void appendCharacterAsPrintFriendlyString(StringBuilder builder, char c) { if (CHARACTER_REPLACEMENTS.containsKey(c)) { builder.append(CHARACTER_REPLACEMENTS.get(c)); } else { builder.append(c); } }
@Test public void testAppendCharacterAsPrintFriendlyString() { StringBuilder builder = null; try { Hl7Util.appendCharacterAsPrintFriendlyString(builder, 'a'); fail("Exception should be raised with null StringBuilder argument"); } catch (NullPointerException ignoredEx...
public void cleanRuleDataSelf(final List<RuleData> ruleDataList) { ruleDataList.forEach(this::removeRuleData); }
@Test public void testCleanRuleDataSelf() throws NoSuchFieldException, IllegalAccessException { RuleData firstCachedRuleData = RuleData.builder().id("1").selectorId(mockSelectorId1).build(); RuleData secondCachedRuleData = RuleData.builder().id("2").selectorId(mockSelectorId2).build(); Concu...
public void close() throws IOException { try { closeAsync().get(); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw new PulsarServerException(e.getCause()); ...
@Test public void testTlsEnabled() throws Exception { final String topicName = "persistent://prop/ns-abc/newTopic"; final String subName = "newSub"; conf.setAuthenticationEnabled(false); conf.setBrokerServicePortTls(Optional.of(0)); conf.setWebServicePortTls(Optional.of(0));...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String c...
@Test public void testAggregateMultipleStatsWhenSomeNullValues() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2"); long[] values1 = { TS_1.getSecondsSinceEpoch(), TS_2.getSecondsSinceEpoch() }; ColumnStatisticsData data1 = new ColStatsBuilder<>(Timestamp.class).numNulls(1)...
private Map<String, Object> getProperties(final Map<String, Object> props) { Map<String, Object> result = new LinkedHashMap<>(props.size(), 1F); for (Entry<String, Object> entry : props.entrySet()) { if (!entry.getKey().contains(".")) { result.put(entry.getKey(), entry.getVal...
@Test void assertGetProperties() { Map<String, Object> actual = new CustomDataSourcePoolProperties( createProperties(), Arrays.asList("username", "password", "closed"), Collections.singletonList("closed"), Collections.singletonMap("username", "user")).getProperties(); assertThat(actu...
public List<SelectorData> obtainSelectorData(final String pluginName) { return SELECTOR_MAP.get(pluginName); }
@Test public void testObtainSelectorData() throws NoSuchFieldException, IllegalAccessException { SelectorData selectorData = SelectorData.builder().id("1").pluginName(mockPluginName1).build(); ConcurrentHashMap<String, List<SelectorData>> selectorMap = getFieldByName(selectorMapStr); selecto...
public static L3ModificationInstruction modArpTpa(IpAddress addr) { checkNotNull(addr, "Dst l3 ARP IP address cannot be null"); return new ModArpIPInstruction(L3SubType.ARP_TPA, addr); }
@Test public void testModArpTpaMethod() { final Instruction instruction = Instructions.modArpTpa(ip41); final L3ModificationInstruction.ModArpIPInstruction modArpIPInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, ...
@Override public void upgrade() { // Only run this migration once. if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } final IndexSetConfig indexSetConfig = findDefaultIndexSet(); fina...
@Test public void upgrade() throws Exception { final Stream stream1 = mock(Stream.class); final Stream stream2 = mock(Stream.class); final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class); when(indexSetService.findAll()).thenReturn(Collections.singletonList(indexSetConfig)...
@Override public Object[] toArray() { return toArray(new Object[size]); }
@Test public void testToGenericArrayReturnsNewArrayWhenSmallArrayProvided() { final OAHashSet<Integer> set = new OAHashSet<>(8); populateSet(set, 10); final Integer[] setElementsProvided = new Integer[9]; final Object[] setElementsReturned = set.toArray(setElementsProvided); ...
public List<CompactionTask> produce() { // get all CF files sorted by key range start (L1+) List<SstFileMetaData> sstSortedByCfAndStartingKeys = metadataSupplier.get().stream() .filter(l -> l.level() > 0) // let RocksDB deal with L0 .sorte...
@Test void testNotGroupingOnDifferentLevels() { SstFileMetaData sst1 = sstBuilder().setLevel(1).build(); SstFileMetaData sst2 = sstBuilder().setLevel(2).build(); assertThat(produce(configBuilder().build(), sst1, sst2)).hasSize(2); }
public static BigDecimal jsToBigNumber( Object value, String classType ) { if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) { return null; } else if ( classType.equalsIgnoreCase( JS_NATIVE_NUM ) ) { Number nb = Context.toNumber( value ); return BigDecimal.valueOf( nb.doubleValue() ); } el...
@Test public void jsToBigNumber_String() throws Exception { assertEquals( BigDecimal.ONE, JavaScriptUtils.jsToBigNumber( "1", String.class.getName() ) ); }
public static LocalDateTime parse(CharSequence text) { return parse(text, (DateTimeFormatter) null); }
@Test public void parseTest5() { final LocalDateTime localDateTime = LocalDateTimeUtil.parse("19940121183604", "yyyyMMddHHmmss"); assertEquals("1994-01-21T18:36:04", Objects.requireNonNull(localDateTime).toString()); }
@Override public Set<Permission> permissions() { return permissions; }
@Test public void immutablePermissions() { // Set<Permission> p = PERMS_ORIG; Set<Permission> p = PERMS_UNSAFE; Application app = baseBuilder.build(); Set<Permission> perms = app.permissions(); try { perms.add(JUNK_PERM); } catch (UnsupportedOperationExce...
public AbilityStatus getConnectionAbility(AbilityKey abilityKey) { if (abilityTable == null || !abilityTable.containsKey(abilityKey.getName())) { return AbilityStatus.UNKNOWN; } return abilityTable.get(abilityKey.getName()) ? AbilityStatus.SUPPORTED : AbilityStatus.NOT_SUPPORTED; ...
@Test void testGetConnectionAbility() { assertFalse(connection.isAbilitiesSet()); assertEquals(AbilityStatus.UNKNOWN, connection.getConnectionAbility(AbilityKey.SDK_CLIENT_TEST_1)); connection.setAbilityTable(Collections.singletonMap(AbilityKey.SERVER_TEST_2.getName(), true)); assert...
@Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException { try (ObjectInputStream ois = new CheckedInputStream(new ByteArrayInputStream(buf), allowList)) { return ois.readObject(); } }
@Test public void testPrimitiveArrays() throws Exception { JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller(); byte[] bytes = marshaller.objectToByteBuffer(Util.EMPTY_BYTE_ARRAY); assertArrayEquals(Util.EMPTY_BYTE_ARRAY, (byte[]) marshaller.objectFromByteBuffer(bytes)); ...
private void doMonitoring(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { if (isRumMonitoring(httpRequest, httpResponse)) { return; } if (!isAllowed(httpRequest, httpResponse)) { return; } final Collector collector = filterContext.getCollecto...
@Test public void testDoMonitoring() throws ServletException, IOException { monitoring(Collections.emptyMap()); monitoring(Collections.singletonMap(HttpParameter.FORMAT, "html")); monitoring(Collections.singletonMap(HttpParameter.FORMAT, "htmlbody")); setProperty(Parameter.DISABLED, Boolean.TRUE.toString()); ...
@JsonProperty("server") public ServerFactory getServerFactory() { return server; }
@Test void hasAnHttpConfiguration() throws Exception { assertThat(configuration.getServerFactory()) .isNotNull(); }
static void setStaticGetter(final RegressionTable regressionTable, final RegressionCompilationDTO compilationDTO, final MethodDeclaration staticGetterMethod, final String variableName) { final BlockStmt regressionTab...
@Test void setStaticGetter() throws IOException { regressionTable = getRegressionTable(3.5, "professional"); RegressionModel regressionModel = new RegressionModel(); regressionModel.setNormalizationMethod(RegressionModel.NormalizationMethod.CAUCHIT); regressionModel.addRegressionTabl...
@GetMapping("/publish/list") @Secured(action = ActionTypes.READ, resource = "nacos/admin") public Result<List<ObjectNode>> getPublishedServiceList(@RequestParam("clientId") String clientId) throws NacosApiException { checkClientId(clientId); Client client = clientManager.getClient(cl...
@Test void testGetPublishedServiceList() throws Exception { // single instance when(clientManager.getClient("test1")).thenReturn(connectionBasedClient); Service service = Service.newService("test", "test", "test"); connectionBasedClient.addServiceInstance(service, new InstancePublish...
@DeleteMapping("/apps/{appId}/clusters/{clusterName:.+}") public void delete(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @RequestParam String operator) { Cluster entity = clusterService.findOne(appId, clusterName); if (entity == null) { th...
@Test(expected = BadRequestException.class) public void testDeleteDefaultFail() { Cluster cluster = new Cluster(); cluster.setName(ConfigConsts.CLUSTER_NAME_DEFAULT); when(clusterService.findOne(any(String.class), any(String.class))).thenReturn(cluster); clusterController.delete("1", "2", "d"); }
public static StatementExecutorResponse execute( final ConfiguredStatement<AssertSchema> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { return AssertExecutor.execute( statement.getMaskedStat...
@Test public void shouldAssertSchemaBySubject() { // Given final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.of("subjectName"), Optional.empty(), Optional.empty(), true); final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement .of(KsqlParser.PreparedStat...
@Udf public Map<String, String> splitToMap( @UdfParameter( description = "Separator string and values to join") final String input, @UdfParameter( description = "Separator string and values to join") final String entryDelimiter, @UdfParameter( description = "Separator s...
@Test public void shouldReturnNullOnNullEntryDelimiter() { Map<String, String> result = udf.splitToMap("foo:=apple/bar:=cherry", null, ":="); assertThat(result, is(nullValue())); }
public static void setRuleMechanism(String ruleMech) { if (ruleMech != null && (!ruleMech.equalsIgnoreCase(MECHANISM_HADOOP) && !ruleMech.equalsIgnoreCase(MECHANISM_MIT))) { throw new IllegalArgumentException("Invalid rule mechanism: " + ruleMech); } ruleMechanism = ruleMech; ...
@Test(expected = IllegalArgumentException.class) public void testInvalidRuleMechanism() throws Exception { KerberosName.setRuleMechanism("INVALID_MECHANISM"); }
public String build( final String cellValue ) { switch ( type ) { case FORALL: return buildForAll( cellValue ); case INDEXED: return buildMulti( cellValue ); default: return buildSingle( cellValue ); } }
@Test public void testForAllOrAndMultipleWithPrefix() { final String snippet = "something == this && forall(||){something == $} && forall(&&){something < $}"; final SnippetBuilder snip = new SnippetBuilder(snippet); final String result = snip.build("x, y"); assertThat(result).isEqual...
public static boolean isValidRootUrl(String url) { UrlValidator validator = new CustomUrlValidator(); return validator.isValid(url); }
@Test public void queryIsForbidden() { // this url will be used as a root url and so will be concatenated with other part, query part is not allowed assertFalse(UrlHelper.isValidRootUrl("http://jenkins?param=test")); assertFalse(UrlHelper.isValidRootUrl("http://jenkins.com?param=test")); ...
@Override protected void runTask() { LOGGER.trace("Looking for succeeded jobs that can go to the deleted state... "); final Instant updatedBefore = now().minus(backgroundJobServerConfiguration().getDeleteSucceededJobsAfter()); processManyJobs(previousResults -> getSucceededJobs(updatedBefore...
@Test void testTask() { Job succeededJob1 = aSucceededJob().build(); Job succeededJob2 = aSucceededJob().build(); when(storageProvider.getJobList(eq(SUCCEEDED), any(), any())).thenReturn(asList(succeededJob1, succeededJob2), emptyJobList()); runTask(task); verify(storageProv...
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final Map<Path, List<ObjectKeyAndVersion>> map = new HashMap<>(); final List<Path> containers = new ArrayList<>(); for(Path file : files.keySet()) { ...
@Test(expected = NotfoundException.class) public void testDeleteNotFoundBucketDnsNameCompatible() throws Exception { final Path container = new Path(new AlphanumericRandomStringService().random().toLowerCase(), EnumSet.of(Path.Type.directory, Path.Type.volume)); new S3MultipleDeleteFeature(session, ...
@Override public void watch(final String key, final DataChangedEventListener dataChangedEventListener) { Watch.Listener listener = Watch.listener(response -> { for (WatchEvent each : response.getEvents()) { Type type = getEventChangedType(each); if (Type.IGNORED !...
@Test void assertWatchUpdate() { doAnswer(invocationOnMock -> { Watch.Listener listener = (Watch.Listener) invocationOnMock.getArguments()[2]; listener.onNext(buildWatchResponse(WatchEvent.EventType.PUT)); return mock(Watch.Watcher.class); }).when(watch).watch(any...
@VisibleForTesting public Map<String, HashSet<String>> runTest(Set<String> inputList, Map<String, Long> sizes) { try { conf = msConf; testDatasizes = sizes; coverageList.clear(); removeNestedStructure(inputList); createOutputList(inputList, "test", "test"); } catch (Exception e)...
@Test public void testGroupLocationsDummyDataSizes() { Set<String> inputLocations = new TreeSet<>(); Configuration conf = MetastoreConf.newMetastoreConf(); MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true); MetaToolTaskListExtTblLocs.msConf = conf; MetaToolTaskListExtTblLoc...
public T get(K key) { T metric = metrics.get(key); if (metric == null) { metric = factory.createInstance(key); metric = MoreObjects.firstNonNull(metrics.putIfAbsent(key, metric), metric); } return metric; }
@Test public void testCreateSeparateInstances() { AtomicLong foo = metricsMap.get("foo"); AtomicLong bar = metricsMap.get("bar"); assertThat(foo, not(sameInstance(bar))); }
@Override public SSLContext getIdentitySslContext() { return sslContext; }
@Test void constructs_ssl_context_from_file() throws IOException { File keyFile = File.createTempFile("junit", null, tempDirectory); KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.RSA); createPrivateKeyFile(keyFile, keypair); X509Certificate certificate = createCertificate(...
public Duration queryTimeout() { return queryTimeout; }
@Test void queryTimeout() { assertThat(builder.build().queryTimeout()).isEqualTo(DEFAULT_QUERY_TIMEOUT); Duration queryTimeout = Duration.ofSeconds(5); builder.queryTimeout(queryTimeout); assertThat(builder.build().queryTimeout()).isEqualTo(queryTimeout); }