focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String getCommandName() { return COMMAND_NAME; }
@Test public void alluxioCmdExecuted() throws IOException, AlluxioException, NoSuchFieldException, IllegalAccessException { CollectAlluxioInfoCommand cmd = new CollectAlluxioInfoCommand(FileSystemContext.create()); // Write to temp dir File targetDir = InfoCollectorTestUtils.createTemporaryDire...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvWithLineFeedAtEnd() { CharSequence value = "testing\n"; CharSequence expected = "\"testing\n\""; escapeCsv(value, expected); }
public Optional<Group> takeGroup(Set<Integer> rejectedGroups) { synchronized (this) { Optional<GroupStatus> best = scheduler.takeNextGroup(rejectedGroups); if (best.isPresent()) { GroupStatus gs = best.get(); gs.allocate(); Group ret = gs....
@Test void requireThatLoadBalancerServesSingleNodeSetups() { Node n1 = new Node("test", 0, "test-node1", 0); LoadBalancer lb = new LoadBalancer(List.of(new Group(0, List.of(n1))), LoadBalancer.Policy.ROUNDROBIN); Optional<Group> grp = lb.takeGroup(null); Group group = grp.orElseThro...
public static MemoryRecords withRecords(Compression compression, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, compression, records); }
@Test public void testUnsupportedCompress() { BiFunction<Byte, CompressionType, MemoryRecords> builderBiFunction = (magic, compressionType) -> MemoryRecords.withRecords(magic, Compression.of(compressionType).build(), new SimpleRecord(10L, "key1".getBytes(), "value1".getBytes())); A...
@Override public Set<String> keySet() { if (this.prefix.isEmpty()) { return this.backingConfig.keySet(); } final HashSet<String> set = new HashSet<>(); int prefixLen = this.prefix.length(); for (String key : this.backingConfig.keySet()) { if (key.sta...
@Test void testDelegationConfigurationWithNullOrEmptyPrefix() { Configuration backingConf = new Configuration(); backingConf.setValueInternal("test-key", "value", false); assertThatThrownBy(() -> new DelegatingConfiguration(backingConf, null)) .isInstanceOf(NullPointerExcept...
public String namespace(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns)); }
@Test public void testNamespaceWithMultipartNamespace() { Namespace ns = Namespace.of("n", "s"); assertThat(withPrefix.namespace(ns)).isEqualTo("v1/ws/catalog/namespaces/n%1Fs"); assertThat(withoutPrefix.namespace(ns)).isEqualTo("v1/namespaces/n%1Fs"); }
@Override public MergeAppend appendFile(DataFile file) { add(file); return this; }
@TestTemplate public void testMergeWithExistingManifestAfterDelete() { // merge all manifests for this test table.updateProperties().set("commit.manifest.min-count-to-merge", "1").commit(); assertThat(listManifestFiles()).isEmpty(); assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0); S...
@Override public boolean match(String attributeValue) { if (attributeValue == null) { return false; } switch (type) { case Equals: return attributeValue.equals(value); case StartsWith: return (length == -1 || length == attributeValue.length()) && ...
@Test public void testSingleCharWildcard() { LikeCondition likeCondition = new LikeCondition("a_b_c"); assertTrue(likeCondition.match("aXbYc")); assertTrue(likeCondition.match("a_b_c")); assertTrue(likeCondition.match("a%b%c")); assertFalse(likeCondition.match("abc")); assertFalse...
@Override public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFetch(final Bytes key) { return wrapped().backwardFetch(key); }
@Test public void shouldDelegateToUnderlyingStoreWhenBackwardFetchingRange() { store.backwardFetch(bytesKey, bytesKey); verify(inner).backwardFetch(bytesKey, bytesKey); }
private static void discovery(XmlGenerator gen, DiscoveryConfig discovery) { if (discovery.getNodeFilter() == null && discovery.getNodeFilterClass() == null && discovery.getDiscoveryStrategyConfigs().isEmpty()) { return; } gen.open("discovery-strategies") ...
@Test public void discovery() { DiscoveryConfig expected = new DiscoveryConfig(); expected.setNodeFilterClass(randomString()); DiscoveryStrategyConfig discoveryStrategy = new DiscoveryStrategyConfig(randomString()); discoveryStrategy.addProperty("prop", randomString()); expec...
static int majorVersionFromJavaSpecificationVersion() { return majorVersion(SystemPropertyUtil.get("java.specification.version", "1.6")); }
@Test public void testMajorVersionFromJavaSpecificationVersion() { final SecurityManager current = System.getSecurityManager(); try { System.setSecurityManager(new SecurityManager() { @Override public void checkPropertyAccess(String key) { ...
public static boolean isNameCoveredByPattern( String name, String pattern ) { if ( name == null || name.isEmpty() || pattern == null || pattern.isEmpty() ) { throw new IllegalArgumentException( "Arguments cannot be null or empty." ); } final String needle = name.toLowerC...
@Test public void testNameCoverageExactMatch() throws Exception { // setup final String name = "xmpp.example.org"; final String pattern = name; // do magic final boolean result = DNSUtil.isNameCoveredByPattern( name, pattern ); // verify assertTrue( resu...
public TreeCache start() throws Exception { Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started"); if (createParentNodes) { client.createContainers(root.path); } client.getConnectionStateListenable().addListener(connectionSt...
@Test public void testChildrenInitialized() throws Exception { client.create().forPath("/test", "".getBytes()); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); client.create().forPath("/test/3", "3".getBytes()); cache =...
public Object toIdObject(String baseId) throws AmqpProtocolException { if (baseId == null) { return null; } try { if (hasAmqpUuidPrefix(baseId)) { String uuidString = strip(baseId, AMQP_UUID_PREFIX_LENGTH); return UUID.fromString(uuidStrin...
@Test public void testToIdObjectWithStringContainingStringEncodingPrefix() throws Exception { String suffix = "myStringSuffix"; String stringId = AMQPMessageIdHelper.AMQP_STRING_PREFIX + suffix; Object idObject = messageIdHelper.toIdObject(stringId); assertNotNull("null object shoul...
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldSendHeartbeatRequest() throws Exception { // Given: KsqlHostInfoEntity entity = new KsqlHostInfoEntity(serverUri.getHost(), serverUri.getPort()); long timestamp = System.currentTimeMillis(); server.setResponseObject(new HeartbeatResponse(true)); // When: KsqlTarget ta...
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) { SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt() .orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo())); SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt() ...
@Test public void testGetNativeSchema() throws SchemaValidationException { JSONSchema<PC> schema2 = JSONSchema.of(PC.class); org.apache.avro.Schema avroSchema2 = (Schema) schema2.getNativeSchema().get(); assertSame(schema2.schema, avroSchema2); }
public static <K, V> Map<K, V> subtractMap(Map<? extends K, ? extends V> minuend, Map<? extends K, ? extends V> subtrahend) { return minuend.entrySet().stream() .filter(entry -> !subtrahend.containsKey(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getVa...
@Test public void testSubtractMapDoesntRemoveAnythingWhenEmptyMap() { Map<String, String> mainMap = new HashMap<>(); mainMap.put("one", "1"); mainMap.put("two", "2"); mainMap.put("three", "3"); Map<String, String> secondaryMap = new HashMap<>(); Map<String, String> n...
static ColumnExtractor create(final Column column) { final int index = column.index(); Preconditions.checkArgument(index >= 0, "negative index: " + index); return column.namespace() == Namespace.KEY ? new KeyColumnExtractor(index) : new ValueColumnExtractor(index); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnNegativeIndex() { // Given: when(column.index()).thenReturn(-1); // When: TimestampColumnExtractors.create(column); }
public static Set<Set<LogicalVertex>> computePipelinedRegions( final Iterable<? extends LogicalVertex> topologicallySortedVertices) { final Map<LogicalVertex, Set<LogicalVertex>> vertexToRegion = PipelinedRegionComputeUtil.buildRawRegions( topologicallySorted...
@Test void testOneInputSplitsIntoTwo() { JobVertex v1 = new JobVertex("v1"); JobVertex v2 = new JobVertex("v2"); JobVertex v3 = new JobVertex("v3"); JobVertex v4 = new JobVertex("v4"); v2.connectNewDataSetAsInput( v1, DistributionPattern.ALL_TO_ALL, ResultPar...
@Override public void doAfterResponse(String remoteAddr, RemotingCommand request, RemotingCommand response) { if (RequestCode.GET_ROUTEINFO_BY_TOPIC != request.getCode()) { return; } if (response == null || response.getBody() == null || ResponseCode.SUCCESS != response.getCode())...
@Test public void testDoAfterResponseWithValidZoneFiltering() throws Exception { HashMap<String, String> extFields = new HashMap<>(); extFields.put(MixAll.ZONE_MODE, "true"); extFields.put(MixAll.ZONE_NAME,"zone1"); RemotingCommand request = RemotingCommand.createRequestCommand(105,n...
public static PointList simplify(ResponsePath responsePath, RamerDouglasPeucker ramerDouglasPeucker, boolean enableInstructions) { final PointList pointList = responsePath.getPoints(); List<Partition> partitions = new ArrayList<>(); // make sure all waypoints are retained in the simplified poin...
@Test public void testSinglePartition() { // points are chosen such that DP will remove those marked with an x // todo: we could go further and replace Ramer-Douglas-Peucker with some abstract thing that makes this easier to test PointList points = new PointList(); points.add(48.8910...
@Override public void yield() throws InterruptedException { Mail mail = mailbox.take(priority); try { mail.run(); } catch (Exception ex) { throw WrappingRuntimeException.wrapIfNecessary(ex); } }
@Test void testYield() throws Exception { final AtomicReference<Exception> exceptionReference = new AtomicReference<>(); final TestRunnable testRunnable = new TestRunnable(); final Thread submitThread = new Thread( () -> { t...
public static HollowSchema parseSchema(String schema) throws IOException { StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(schema)); configureTokenizer(tokenizer); return parseSchema(tokenizer); }
@Test public void parsesMapSchemaWithMultiFieldPrimaryKey() throws IOException { String listSchema = "MapOfStringToTypeA Map<String, TypeA> @HashKey(id.value, region.country.id, key);\n"; HollowMapSchema schema = (HollowMapSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEq...
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void returnOnCompleteUsingMaybe() throws InterruptedException { RetryConfig config = retryConfig(); Retry retry = Retry.of("testName", config); RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry); given(helloWorldService.returnHelloWorld()) ...
@GwtIncompatible("java.util.regex.Pattern") public void containsMatch(@Nullable Pattern regex) { checkNotNull(regex); if (actual == null) { failWithActual("expected a string that contains a match for", regex); } else if (!regex.matcher(actual).find()) { failWithActual("expected to contain a ma...
@Test @GwtIncompatible("Pattern") public void stringContainsMatchPatternFailNull() { expectFailureWhenTestingThat(null).containsMatch(Pattern.compile(".*b.*")); assertFailureValue("expected a string that contains a match for", ".*b.*"); }
@Override public InterpreterResult interpret(String cypherQuery, InterpreterContext interpreterContext) { LOGGER.info("Opening session"); if (StringUtils.isBlank(cypherQuery)) { return new InterpreterResult(Code.SUCCESS); } final List<String> queries = isMultiStatementEnabled ? Array...
@Test void testNodeDataTypes() throws IOException { InterpreterResult result = interpreter.interpret( "CREATE (n:NodeTypes{" + "dateTime: datetime('2015-06-24T12:50:35.556+0100')," + "point3d: point({ x:0, y:4, z:1 })})\n" + "RETURN n", ...
@NonNull public static String objectToJson(@NonNull Object source) { Assert.notNull(source, "Source object must not be null"); try { return DEFAULT_JSON_MAPPER.writeValueAsString(source); } catch (JsonProcessingException e) { throw new JsonParseException(e); }...
@Test public void serializerTime() { Instant now = Instant.now(); String instantStr = JsonUtils.objectToJson(now); assertThat(instantStr).isNotNull(); String localDateTimeStr = JsonUtils.objectToJson(LocalDateTime.now()); assertThat(localDateTimeStr).isNotNull(); }
@Override public List<ClusterNodeInfo> decode(ByteBuf buf, State state) throws IOException { String response = buf.toString(CharsetUtil.UTF_8); List<ClusterNodeInfo> nodes = new ArrayList<>(); for (String nodeInfo : response.split("\n")) { ClusterNodeInfo node = new Clus...
@Test public void test() throws IOException { ClusterNodesDecoder decoder = new ClusterNodesDecoder(false); ByteBuf buf = Unpooled.buffer(); String info = "7af253f8c20a3b3fbd481801bd361ec6643c6f0b 192.168.234.129:7001@17001 master - 0 1478865073260 8 connected 5461-10922\n" + ...
public static String getTypeStrFromProto(Descriptors.FieldDescriptor desc) { switch (desc.getJavaType()) { case INT: return "Integer"; case LONG: return "Long"; case STRING: return "String"; case FLOAT: return "Float"; case DOUBLE: return "Double...
@Test(dataProvider = "typeCases") public void testGetTypeStrFromProto(String fieldName, String javaType) { Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(fieldName); Assert.assertEquals(ProtoBufUtils.getTypeStrFromProto(fd), javaType); }
public static Build withPropertyValue(String propertyValue) { return new Builder(propertyValue); }
@Test void it_should_return_unknown_when_property_value_does_not_exist() { //GIVEN String unknownValue = "an_unknown_value"; //WHEN ElasticsearchClientType esClientType = ElasticsearchClientTypeBuilder.withPropertyValue(unknownValue).build(); //THEN assertEquals(UNKNOWN, esClientType);...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, String.valueOf(Path.DELIMITER)); }
@Test public void testListFile() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final String name = new AlphanumericRandomStringService().random(); final Path file = new S3TouchFeature(session, new S3Acces...
public AggregationType computeAggregationType(String name) { return this.aggregationAssessor.computeAggregationType(name); }
@Test public void bridgeMethodsShouldBeIgnored() { Orange orange = new Orange(); PropertySetter orangeSetter = new PropertySetter(new BeanDescriptionCache(context), orange); assertEquals(AggregationType.AS_BASIC_PROPERTY, orangeSetter.computeAggregationType(Citrus.PRECARP_PR...
public ByteBuffer getByteBuffer() { ByteBuffer byteBuffer = ByteBuffer.allocate(32); byteBuffer.putInt(0, hashCode); byteBuffer.putInt(4, topicId); byteBuffer.putInt(8, queueId); byteBuffer.putLong(12, offset); byteBuffer.putInt(20, size); byteBuffer.putInt(24, ti...
@Test public void getByteBufferTest() { IndexItem indexItem = new IndexItem(topicId, queueId, offset, size, hashCode, timeDiff, itemIndex); ByteBuffer byteBuffer = indexItem.getByteBuffer(); Assert.assertEquals(hashCode, byteBuffer.getInt(0)); Assert.assertEquals(topicId, byteBuffer....
@Override public boolean syncClientConnected(String clientId, ClientAttributes attributes) { throw new UnsupportedOperationException(""); }
@Test void makeSureSyncClientConnected() { assertThrows(UnsupportedOperationException.class, () -> { persistentIpPortClientManager.syncClientConnected(clientId, clientAttributes); }); }
@Operation(summary = "createUser", description = "CREATE_USER_NOTES") @Parameters({ @Parameter(name = "userName", description = "USER_NAME", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "userPassword", description = "USER_PASSWORD", required = true, sc...
@Test public void testCreateUser() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userName", "user_test"); paramsMap.add("userPassword", "123456qwe?"); paramsMap.add("tenantId", "109"); paramsMap.add("queue", "1"); ...
public final void isZero() { if (actual == null || actual.floatValue() != 0.0f) { failWithActual(simpleFact("expected zero")); } }
@Test public void isZero() { assertThat(0.0f).isZero(); assertThat(-0.0f).isZero(); assertThatIsZeroFails(Float.MIN_VALUE); assertThatIsZeroFails(-1.23f); assertThatIsZeroFails(Float.POSITIVE_INFINITY); assertThatIsZeroFails(Float.NaN); assertThatIsZeroFails(null); }
@Override public boolean supportsDifferentTableCorrelationNames() { return false; }
@Test void assertSupportsDifferentTableCorrelationNames() { assertFalse(metaData.supportsDifferentTableCorrelationNames()); }
public CeTaskMessageDto setMessage(String message) { checkArgument(message != null && !message.isEmpty(), "message can't be null nor empty"); this.message = abbreviate(message, MAX_MESSAGE_SIZE); return this; }
@Test void setMessage_fails_with_IAE_if_argument_is_empty() { assertThatThrownBy(() -> underTest.setMessage("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("message can't be null nor empty"); }
@Override public boolean contains(K name) { return get(name) != null; }
@Test public void testContains() { TestDefaultHeaders headers = newInstance(); headers.addBoolean(of("boolean"), true); assertTrue(headers.containsBoolean(of("boolean"), true)); assertFalse(headers.containsBoolean(of("boolean"), false)); headers.addLong(of("long"), Long.MAX_...
String getPasswordFromCredentialProviders( Configuration config, String alias, String defaultPass) { String password = defaultPass; try { char[] passchars = config.getPasswordFromCredentialProviders(alias); if (passchars != null) { password = new String(passchars); } } catch ...
@Test public void testConfGetPasswordUsingAlias() throws Exception { File testDir = GenericTestUtils.getTestDir(); Configuration conf = getBaseConf(); final Path jksPath = new Path(testDir.toString(), "test.jks"); final String ourUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toU...
public String getInverseAddressFormat(String ipAddress) { ipAddress = StringUtils.trim(ipAddress); validateIpAddress(ipAddress); LOG.debug("Preparing inverse format for IP address [{}]", ipAddress); // Detect what type of address is provided (IPv4 or IPv6) if (isIp6Address(ip...
@Test public void testReverseIpFormat() { DnsClient dnsClient = new DnsClient(5000); // Test IPv4 reverse format. assertEquals("40.30.20.10.in-addr.arpa.", dnsClient.getInverseAddressFormat("10.20.30.40")); // Test IPv6 reverse format. assertEquals("1.0.0.b.1.a.7.0.0.0.0.0...
@Override public void setCurrentKey(Object key) {}
@SuppressWarnings("LockNotBeforeTry") @Test public void testEnsureStateCleanupWithKeyedInputCleanupTimer() { InMemoryTimerInternals inMemoryTimerInternals = new InMemoryTimerInternals(); KeyedStateBackend keyedStateBackend = Mockito.mock(KeyedStateBackend.class); Lock stateBackendLock = Mockito.mock(Loc...
@SuppressWarnings("ReturnOfNull") @Override public String getCatalog() { try { return connection.getCatalog(); } catch (final SQLException ignored) { return null; } }
@Test void assertGetCatalogReturnNullWhenThrowsSQLException() throws SQLException { when(connection.getCatalog()).thenThrow(SQLException.class); MetaDataLoaderConnection connection = new MetaDataLoaderConnection(databaseType, this.connection); assertNull(connection.getCatalog()); }
@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() { SentinelSofaRpcProviderFilter filter = new SentinelSofaRpcProviderFilter(); final String applicationName = "demo-provider"; final String interfaceResourceName = "com.alibaba.csp.sentinel.adapter.sofa.rpc.service.DemoService"; final Strin...
@Override public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", namespaceId, serviceName, instance); String groupedServiceName = NamingUtils.get...
@Test void testRegisterServiceThrowsException() throws Exception { assertThrows(NacosException.class, () -> { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult<Object> a = new HttpRestResult<Object>(); a.setCode(503); ...
public static void warn(final Logger logger, final String format, final Supplier<Object> supplier) { if (logger.isWarnEnabled()) { logger.warn(format, supplier.get()); } }
@Test public void testNeverWarnWithFormat() { when(logger.isWarnEnabled()).thenReturn(false); LogUtils.warn(logger, "testWarn: {}", supplier); verify(supplier, never()).get(); }
@Override public void handleEventFromOperator(int subtask, int attemptNumber, OperatorEvent event) { DynamicFilteringData currentData = ((DynamicFilteringEvent) ((SourceEventWrapper) event).getSourceEvent()).getData(); if (receivedFilteringData == null) { receivedFilterin...
@Test void testRedistributeData() throws Exception { MockOperatorCoordinatorContext context = new MockOperatorCoordinatorContext(new OperatorID(), 1); String listenerID1 = "test-listener-1"; String listenerID2 = "test-listener-2"; TestingOperatorCoordinator listener1...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { if (stream == null) { throw new NullPointerException("null stream"); } Throwable t; boolean alive =...
@Test public void testParallelParsing() throws Exception { try (ForkParser parser = new ForkParser(ForkParserTest.class.getClassLoader(), new ForkTestParser())) { final ParseContext context = new ParseContext(); Thread[] threads = new Thread[10]; ContentH...
public Properties createProperties(Props props, File logDir) { Log4JPropertiesBuilder log4JPropertiesBuilder = new Log4JPropertiesBuilder(props); RootLoggerConfig config = newRootLoggerConfigBuilder() .setNodeNameField(getNodeNameWhenCluster(props)) .setProcessId(ProcessId.ELASTICSEARCH) .buil...
@Test public void createProperties_sets_root_logger_to_INFO_if_no_property_is_set() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties(newProps(), logDir); assertThat(properties.getProperty("rootLogger.level")).isEqualTo("INFO"); }
@Override public void setKeyboardTheme(@NonNull KeyboardTheme theme) { super.setKeyboardTheme(theme); mExtensionKeyboardYDismissPoint = getThemedKeyboardDimens().getNormalKeyHeight(); mGestureDrawingHelper = GestureTypingPathDrawHelper.create( this::invalidate, GestureTra...
@Test public void testMinimumPadding() { final Resources resources = mViewUnderTest.getContext().getResources(); final int minimumBottomPadding = resources.getDimensionPixelOffset(R.dimen.watermark_margin) + resources.getDimensionPixelOffset(R.dimen.watermark_size); Assert.assertTrue( ...
@Override public boolean isEmpty() { reap(); return backingStore.isEmpty(); }
@Test void stressMap() { for (int i = 1; i <= TEST_SIZE; i++) { data.add("Data_" + i); } List<Thread> threads = new ArrayList<>(80); for (int i = 0; i <= 80; i++) { final int seed = (i + 1) * 100; Runnable runnable = () -> rundata(seed); Thread t = new Thread(runnable); ...
public static File file(String path) { if (null == path) { return null; } return new File(getAbsolutePath(path)); }
@Test public void fileTest1() { final File file = FileUtil.file("d:/aaa", "bbb"); assertNotNull(file); }
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) { SinkConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!existingC...
@Test public void testMergeDifferentTransformFunctionClassName() { SinkConfig sinkConfig = createSinkConfig(); String newFunctionClassName = "NewTransformFunction"; SinkConfig newSinkConfig = createUpdatedSinkConfig("transformFunctionClassName", newFunctionClassName); SinkConfig merg...
@Override @MethodNotAvailable public Map<K, Object> executeOnEntries(com.hazelcast.map.EntryProcessor entryProcessor) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testExecuteOnEntriesWithPredicate() { adapter.executeOnEntries(new IMapReplaceEntryProcessor("value", "newValue"), Predicates.alwaysTrue()); }
@Override public boolean add(final Integer value) { return add(value.intValue()); }
@Test public void setsWithTheSameValuesAreEqual() { final IntHashSet other = new IntHashSet(100, -1); set.add(1); set.add(1001); other.add(1); other.add(1001); assertEquals(set, other); }
@Override public RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroup(String groupId, RemoveMembersFromConsumerGroupOptions options) { String reason = options.reason() == null || options.reason().isEmpty() ? ...
@Test public void testRemoveMembersFromGroupRetriableErrors() throws Exception { // Retriable errors should be retried try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafk...
public double maxQueryGrowthRate(Duration window, Instant now) { if (snapshots.isEmpty()) return 0.1; // Find the period having the highest growth rate, where total growth exceeds 30% increase double maxGrowthRate = 0; // In query rate growth per second (to get good resolution) for (int...
@Test public void test_empty() { ManualClock clock = new ManualClock(); var timeseries = new ClusterTimeseries(cluster, List.of()); assertEquals(0.1, timeseries.maxQueryGrowthRate(Duration.ofMinutes(5), clock.instant()), delta); }
@Udf public <T> Integer calcArrayLength( @UdfParameter(description = "The array") final List<T> array ) { if (array == null) { return null; } return array.size(); }
@Test public void shouldReturnArraySize() { assertThat(udf.calcArrayLength(ImmutableList.of()), is(0)); assertThat(udf.calcArrayLength(ImmutableList.of(1)), is(1)); assertThat(udf.calcArrayLength(ImmutableList.of("one", "two")), is(2)); }
public static <T> RetryOperator<T> of(Retry retry) { return new RetryOperator<>(retry); }
@Test public void retryOnResultFailAfterMaxAttemptsWithExceptionUsingFlux() { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(10)) .maxAttempts(3) .failAfterMaxAttempts(true) .build(...
public String getFileName() { return fileName; }
@Test void getFileName() { LocalPredictionId retrieved = new LocalPredictionId(fileName, name); assertThat(retrieved.getFileName()).isEqualTo(fileName); }
public void clear() { NamedClusterServiceOsgi ncso = meta.getNamedClusterServiceOsgi(); if ( ncso != null ) { //Don't kill the embedded if we don't have the service to rebuild addedAllClusters = false; addedAnyClusters = false; // The embeddedMetaStoreFactory may be null if creating a brand n...
@Test public void testClear() throws Exception { when( mockMetaStoreFactory.getElements() ) .thenReturn( Arrays.asList( mockNamedCluster1, mockNamedCluster2 ) ); namedClusterEmbedManager.clear( ); verify( mockMetaStoreFactory ).deleteElement( CLUSTER1_NAME ); verify( mockMetaStoreFactory ).dele...
@Override public void checkAuthorization( final KsqlSecurityContext securityContext, final MetaStore metaStore, final Statement statement ) { if (statement instanceof Query) { validateQuery(securityContext, metaStore, (Query)statement); } else if (statement instanceof InsertInto) { ...
@Test public void shouldThrowWhenCreateAsSelectWithoutReadPermissionsDenied() { // Given: givenTopicAccessDenied(KAFKA_TOPIC, AclOperation.READ); final Statement statement = givenStatement(String.format( "CREATE STREAM newStream AS SELECT * FROM %s;", KAFKA_STREAM_TOPIC) ); // When: f...
public static StatementExecutorResponse execute( final ConfiguredStatement<CreateConnector> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final CreateConnector createConnector = statement.getStatem...
@Test public void shouldReturnWarningOnExecuteWhenIfNotExistsSetConnectorExists() { //Given: givenConnectorExists(); //When final Optional<KsqlEntity> entity = ConnectExecutor .execute(CREATE_DUPLICATE_CONNECTOR_CONFIGURED, mock(SessionProperties.class), null, serviceContext).getE...
public static int appendArchiveIdLabel( final MutableDirectBuffer tempBuffer, final int offset, final long archiveId) { int suffixLength = 0; suffixLength += tempBuffer.putStringWithoutLengthAscii(offset, ARCHIVE_ID_LABEL_PREFIX); suffixLength += tempBuffer.putLongAscii(offset + suff...
@Test void appendArchiveIdLabel() { final int offset = 13; final long archiveId = -23462384L; final UnsafeBuffer buffer = new UnsafeBuffer(new byte[100]); final int length = ArchiveCounters.appendArchiveIdLabel(buffer, offset, archiveId); assertEquals(ArchiveCounters.le...
@Override public void trackViewAppClick(View view) { }
@Test public void trackViewAppClick() { View view = new View(mApplication); mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); ...
@Override protected Result[] run(String value) { final Map<String, Object> extractedJson; try { extractedJson = extractJson(value); } catch (IOException e) { throw new ExtractorException(e); } final List<Result> results = new ArrayList<>(extractedJson....
@Test public void testRunWithNullInput() throws Exception { assertThat(jsonExtractor.run(null)).isEmpty(); }
public static <E, T> List<T> toList(Collection<E> collection, Function<E, T> function) { return toList(collection, function, false); }
@Test public void testTranslate2List() { List<String> list = CollStreamUtil.toList(null, Student::getName); assertEquals(list, Collections.EMPTY_LIST); List<Student> students = new ArrayList<>(); list = CollStreamUtil.toList(students, Student::getName); assertEquals(list, Collections.EMPTY_LIST); students....
public static Map<String, String> labels(RunContext runContext, String prefix) { return labels(runContext, prefix, true, false); }
@Test void labels() { var runContext = runContext(runContextFactory, "very.very.very.very.very.very.very.very.very.very.very.very.long.namespace"); var labels = ScriptService.labels(runContext, "kestra.io/"); assertThat(labels.size(), is(6)); assertThat(labels.get("kestra.io/namespa...
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testInOperand() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); SearchArgument arg = builder.startAnd().in("salary", PredicateLeaf.Type.LONG, 3000L, 4000L).end().build(); UnboundPredicate expected = Expressions.in("salary", 3000L, 4000L); UnboundPredic...
public RMNode selectLocalNode( String hostName, Set<String> blacklist, Resource request) { if (blacklist.contains(hostName)) { return null; } RMNode node = nodeByHostName.get(hostName); if (node != null) { ClusterNode clusterNode = clusterNodes.get(node.getNodeID()); if (clusterN...
@Test public void testSelectLocalNode() { NodeQueueLoadMonitor selector = new NodeQueueLoadMonitor( NodeQueueLoadMonitor.LoadComparator.QUEUE_LENGTH); RMNode h1 = createRMNode("h1", 1, -1, 2, 5); RMNode h2 = createRMNode("h2", 2, -1, 5, 5); RMNode h3 = createRMNode("h3", 3, -1, 4, 5); se...
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@Test public void testUnpartitionedDays() throws Exception { createUnpartitionedTable(spark, tableName); SparkScanBuilder builder = scanBuilder(); DaysFunction.TimestampToDaysFunction function = new DaysFunction.TimestampToDaysFunction(); UserDefinedScalarFunc udf = toUDF(function, expressions(field...
static ProcessorSupplier readMapIndexSupplier(MapIndexScanMetadata indexScanMetadata) { return new MapIndexScanProcessorSupplier(indexScanMetadata); }
@Test public void test_fullScanDesc_sorted() { List<JetSqlRow> expected = new ArrayList<>(); for (int i = 0; i <= count; i++) { map.put(i, new Person("value-" + i, i)); expected.add(jetRow((count - i), "value-" + (count - i), (count - i))); } IndexConfig inde...
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder) throws CoderException { if (value == null) { return noopMutationDetector(); } else { return new CodedValueMutationDetector<>(value, coder); } }
@Test public void testMutationWithEqualEncodings() throws Exception { class EncodingBadStructuralValueCoder extends AtomicCoder<List<Object>> { @Override public void encode(List<Object> value, OutputStream outStream) throws CoderException, IOException { outStream.write(new byte[] {1,...
private static JiffiesAndCpus getTotalSystemJiffies() { try { BufferedReader in = new BufferedReader(new FileReader("/proc/stat")); return getTotalSystemJiffies(in); } catch (FileNotFoundException ex) { log.log(Level.SEVERE, "Unable to open stat file", ex); ...
@Test public void testTotalJiffies() { SystemPoller.JiffiesAndCpus first = SystemPoller.getTotalSystemJiffies(new BufferedReader(new StringReader(totalStats[0]))); SystemPoller.JiffiesAndCpus second = SystemPoller.getTotalSystemJiffies(new BufferedReader(new StringReader(totalStats[1]))); ...
public Result runIndexOrPartitionScanQueryOnOwnedPartitions(Query query) { Result result = runIndexOrPartitionScanQueryOnOwnedPartitions(query, true); assert result != null; return result; }
@Test public void verifyIndexedQueryFailureWhileMigratingInFlight() { map.addIndex(IndexType.HASH, "this"); EqualPredicate predicate = new EqualPredicate("this", value) { @Override public Set<QueryableEntry> filter(QueryContext queryContext) { // start a new ...
@DeleteMapping("/batch") @RequiresPermissions("system:pluginHandler:delete") public ShenyuAdminResult deletePluginHandles(@RequestBody @NotEmpty final List<@NotBlank String> ids) { return ShenyuAdminResult.success(ShenyuResultMessage.DELETE_SUCCESS, pluginHandleService.deletePluginHandles(ids)); }
@Test public void testDeletePluginHandles() throws Exception { given(this.pluginHandleService.deletePluginHandles(Collections.singletonList("1"))).willReturn(1); this.mockMvc.perform(MockMvcRequestBuilders.delete("/plugin-handle/batch", "1") .contentType(MediaType.APPLICATION...
@Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { switch(response.getStatusLine().getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: try { log.info(String.format("Attempt to refresh ...
@Test public void retryRequest() { final ServiceUnavailableRetryStrategy handler = new CustomServiceUnavailableRetryStrategy(session.getHost(), 2, new ExecutionCountServiceUnavailableRetryStrategy(1, session.authentication)); assertTrue(handler.retryRequest( ...
public List<DeviceId> devices() { return object.has(DEVICES) ? getList(DEVICES, DeviceId::deviceId) : null; }
@Test public void modifyDevices() { loadRegion(R3); cfg.devices(ALT_DEVICES); checkRegion(R3, null, ALT_DEVICES); }
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { if (readerWay.hasTag("hazmat:water", "no")) { hazWaterEnc.setEnum(false, edgeId, edgeIntAccess, HazmatWater.NO); } else if (readerWay.hasTag("hazmat:water", "permiss...
@Test public void testSimpleTags() { ReaderWay readerWay = new ReaderWay(1); EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; readerWay.setTag("hazmat:water", "no"); parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags); assertEquals...
@Override public DescriptiveUrl toUploadUrl(final Path file, final Sharee sharee, final Void options, final PasswordCallback callback) throws BackgroundException { try { final Host bookmark = session.getHost(); final CreateFileShareRequest request = new CreateFileShareRequest() ...
@Test public void toUploadUrl() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), ...
public static GetApplicationsResponse mergeApplications( Collection<GetApplicationsResponse> responses, boolean returnPartialResult){ Map<ApplicationId, ApplicationReport> federationAM = new HashMap<>(); Map<ApplicationId, ApplicationReport> federationUAMSum = new HashMap<>(); for (GetApplicati...
@Test public void testMergeApplicationsNullResourceUsage() { ApplicationId appId = ApplicationId.newInstance(1234, 1); ApplicationReport appReport = ApplicationReport.newInstance( appId, ApplicationAttemptId.newInstance(appId, 1), "user", "queue", "app1", "host", 124, null, YarnApplica...
List<String> doRetrieve(GroupVersionKind type, ListOptions options, Sort sort) { var indexer = indexerFactory.getIndexer(type); StopWatch stopWatch = new StopWatch(type.toString()); stopWatch.start("Check index status to ensure all indexes are ready"); var fieldNamesUsedInQuery = getFi...
@Test void doRetrieve() { var indexer = mock(Indexer.class); var gvk = GroupVersionKind.fromExtension(DemoExtension.class); when(indexerFactory.getIndexer(eq(gvk))).thenReturn(indexer); pileForIndexer(indexer, PrimaryKeySpecUtils.PRIMARY_INDEX_NAME, List.of( Map.entry(...
@Override public void removeConfigInfo(final String dataId, final String group, final String tenant, final String srcIp, final String srcUser) { final Timestamp time = new Timestamp(System.currentTimeMillis()); ConfigInfo configInfo = findConfigInfo(dataId, group, tenant); if (Ob...
@Test void testRemoveConfigInfo() { String dataId = "dataId4567"; String group = "group3456789"; String tenant = "tenant4567890"; //mock exist config info ConfigInfoWrapper configInfoWrapperOld = new ConfigInfoWrapper(); configInfoWrapperOld.setDataId(dataId)...
public CoercedExpressionResult coerce() { final Class<?> leftClass = left.getRawClass(); final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass); final Class<?> rightClass = right.getRawClass(); final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass); ...
@Test public void doNotCastNumberLiteralInt() { final TypedExpression left = expr("getValue()", java.lang.Object.class); final TypedExpression right = expr("20", int.class); final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, false).coerce(); a...
@VisibleForTesting MatchResult expand(GcsPath gcsPattern) throws IOException { String prefix = GcsUtil.getNonWildcardPrefix(gcsPattern.getObject()); Pattern p = Pattern.compile(wildcardToRegexp(gcsPattern.getObject())); LOG.debug( "matching files in bucket {}, prefix {} against pattern {}", ...
@Test public void testExpandNonGlob() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Glob expression: [testdirectory/otherfile] is not expandable."); gcsFileSystem.expand(GcsPath.fromUri("gs://testbucket/testdirectory/otherfile")); }
@Override public ListenableFuture<SplitBatch> getNextBatch(ConnectorPartitionHandle partitionHandle, Lifespan lifespan, int maxSize) { checkArgument(maxSize > 0, "Cannot fetch a batch of zero size"); return GetNextBatch.fetchNextBatchAsync(source, Math.min(bufferSize, maxSize), maxSize, partitio...
@Test public void testFail() { MockSplitSource mockSource = new MockSplitSource() .setBatchSize(1) .increaseAvailableSplits(1) .atSplitCompletion(FAIL); try (SplitSource source = new BufferingSplitSource(mockSource, 100)) { assertFuture...
public static GrpcServerExecutorMetric getSdkServerExecutorMetric() { return sdkServerExecutorMetric; }
@Test void testSdkServerExecutorMetric() { MetricsMonitor.getSdkServerExecutorMetric().getPoolSize().set(1); MetricsMonitor.getSdkServerExecutorMetric().getMaximumPoolSize().set(1); MetricsMonitor.getSdkServerExecutorMetric().getCorePoolSize().set(1); MetricsMonitor.getSdkServerExecu...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_parse_date_value() { // Given String queries = "@prepare[parse_date]=INSERT INTO zeppelin.users(login,last_update) " + "VALUES(?,?)\n" + "@bind[parse_date]='last_update','2015-07-30 12:00:01'\n" + "SELECT last_update FROM zeppelin.users WHERE login='last_update';"; ...
@Override public boolean test(final Path test) { return this.equals(new DefaultPathPredicate(test)); }
@Test public void testPredicateVersionIdFile() { final Path t = new Path("/f", EnumSet.of(Path.Type.file), new PathAttributes().withVersionId("1")); assertTrue(new DefaultPathPredicate(t).test(t)); assertTrue(new DefaultPathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.file), new Pat...
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testDeterminismUnion() { assertDeterministic(AvroCoder.of(DeterministicUnionBase.class)); assertNonDeterministic( AvroCoder.of(NonDeterministicUnionBase.class), reasonField(UnionCase3.class, "mapField", "may not be deterministically ordered")); }
public static AS2MessageDispositionNotificationEntity parseDispositionNotification( List<CharArrayBuffer> dispositionNotificationFields) throws ParseException { String reportingUA = null; String mtaName = null; String finalRecipient = null; String originalMessageI...
@Test public void test() throws Exception { InputStream is = new ByteArrayInputStream(DISPOSITION_NOTIFICATION_CONTENT.getBytes()); AS2SessionInputBuffer inbuffer = new AS2SessionInputBuffer(new BasicHttpTransportMetrics(), 8 * 1024); List<CharArrayBuffer> dispositionNotificationFields ...
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()); sb.append(" [HTTP Status:").append(_status == null ? "null" : _status.getCode()); if (_serviceErrorCode != null) { sb.append(", serviceErrorCode:").append(_serviceErrorCode); ...
@Test public void testNullStatus() { final RestLiServiceException restLiServiceException = new RestLiServiceException((HttpStatus) null); Assert.assertTrue(restLiServiceException.toString().contains("[HTTP Status:null]")); }
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema == null && value == null) { return null; } JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value); ...
@Test public void floatToJson() { JsonNode converted = parse(converter.fromConnectData(TOPIC, Schema.FLOAT32_SCHEMA, 12.34f)); validateEnvelope(converted); assertEquals(parse("{ \"type\": \"float\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)); asser...
@Override public KeyValueIterator<K, V> reverseRange(final K from, final K to) { final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = new NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>>() { @Override public KeyValueIterator<K, V> apply(final Re...
@Test public void shouldSupportReverseRangeAcrossMultipleKVStores() { final KeyValueStore<String, String> cache = newStoreInstance(); stubProviderTwo.addStore(storeName, cache); stubOneUnderlying.put("a", "a"); stubOneUnderlying.put("b", "b"); stubOneUnderlying.put("z", "z")...
public static @Nullable CastRule<?, ?> resolve(LogicalType inputType, LogicalType targetType) { return INSTANCE.internalResolve(inputType, targetType); }
@Test void testResolveDistinctTypeToIdentityCastRule() { assertThat(CastRuleProvider.resolve(DISTINCT_INT, INT)).isSameAs(IdentityCastRule.INSTANCE); assertThat(CastRuleProvider.resolve(INT, DISTINCT_INT)).isSameAs(IdentityCastRule.INSTANCE); assertThat(CastRuleProvider.resolve(DISTINCT_INT,...
public boolean isEnabled() { return !allowedCpusList.isEmpty(); }
@Test public void whenRange() { ThreadAffinity threadAffinity = new ThreadAffinity("1-4"); assertTrue(threadAffinity.isEnabled()); assertEquals(4, threadAffinity.allowedCpusList.size()); assertEquals(threadAffinity.allowedCpusList.get(0), newBitset(1)); assertEquals(threadAf...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithTime() throws SQLException { Time result = mock(Time.class); when(mergeResultSet.getValue(1, Time.class)).thenReturn(result); assertThat(shardingSphereResultSet.getObject(1, Time.class), is(result)); }
@Udf(description = "Converts a string representation of a date in the given format" + " into the number of days since 1970-01-01 00:00:00 UTC/GMT.") public int stringToDate( @UdfParameter( description = "The string representation of a date.") final String formattedDate, @UdfParameter( ...
@Test public void shouldConvertStringToDate() { // When: final int result = udf.stringToDate("2021-12-01", "yyyy-MM-dd"); // Then: assertThat(result, is(18962)); }
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { String surfaceTag = readerWay.getTag("surface"); Surface surface = Surface.find(surfaceTag); if (surface == MISSING) return; surfaceEnc.setEnum(fals...
@Test public void testSubtypes() { IntsRef relFlags = new IntsRef(2); ReaderWay readerWay = new ReaderWay(1); EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; readerWay.setTag("highway", "primary"); readerWay.setTag("surface", "concrete:plates"...
@Override public void done(RouteMetricSet metrics) { try { output.println("# Time used, num ok, num error, min latency, max latency, average latency"); printMetrics(output, metrics); } catch (Exception e) { e.printStackTrace(); } }
@Test void testSimple() { ByteArrayOutputStream output = new ByteArrayOutputStream(); ManualTimer timer = new ManualTimer(); BenchmarkProgressPrinter printer = new BenchmarkProgressPrinter(timer, new PrintStream(output)); RouteMetricSet metrics = new RouteMetricSet("foobar", timer, p...