focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public String toTypeString() { // needs a map instead of switch because for some reason switch creates an // internal class with no annotations that messes up EntityTest return Optional.ofNullable(TO_TYPE_STRING.getOrDefault(type, si -> si.type.name())) .orElseThrow(NullPointerException::new).apply(...
@Test public void shouldCorrectlyFormatDecimalsWithPrecisionAndScale() { final SchemaInfo schemaInfo= new SchemaInfo( SqlBaseType.DECIMAL, null, null, ImmutableMap.of("precision", 10, "scale", 9) ); assertThat(schemaInfo.toTypeString(), equalTo("DECIMAL(10,...
public void shutdown() { stopReconstructionInitializer(); blocksMap.close(); MBeans.unregister(mxBeanName); mxBeanName = null; }
@Test (timeout = 300000) public void testPlacementPolicySatisfied() throws Exception { LOG.info("Starting testPlacementPolicySatisfied."); final String[] initialRacks = new String[]{ "/rack0", "/rack1", "/rack2", "/rack3", "/rack4", "/rack5"}; final String[] initialHosts = new String[]{ "h...
@Override public TimelineEntity getApplicationAttemptEntity( ApplicationAttemptId appAttemptId, String fields, Map<String, String> filters) throws IOException { ApplicationId appId = appAttemptId.getApplicationId(); String path = PATH_JOINER.join("clusters", clusterId, "apps", appId, "enti...
@Test void getApplicationAttemptEntity() throws Exception { ApplicationAttemptId attemptId = ApplicationAttemptId.fromString("appattempt_1234_0001_000001"); TimelineEntity entity = client.getApplicationAttemptEntity(attemptId, null, null); assertEquals("mockAppAttempt1", entity.getId()); ...
@Override public byte[] serialize(Event event) { if (event instanceof SchemaChangeEvent) { Schema schema; SchemaChangeEvent schemaChangeEvent = (SchemaChangeEvent) event; if (event instanceof CreateTableEvent) { CreateTableEvent createTableEvent = (CreateT...
@Test public void testSerialize() throws Exception { ObjectMapper mapper = JacksonMapperFactory.createObjectMapper() .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, false); SerializationSchema<Event> serializationSchema = ChangeLogJ...
@Override public Collection<Permission> getPermissions(Action action) { if (!(action instanceof DestinationAction)) { throw new IllegalArgumentException("Action argument must be a " + DestinationAction.class.getName() + " instance."); } DestinationAction da = (DestinationAction) ...
@Test public void testGetPermissionsWithTopic() { ActiveMQTopic topic = new ActiveMQTopic("myTopic"); DestinationAction action = new DestinationAction(new ConnectionContext(), topic, "create"); Collection<Permission> perms = resolver.getPermissions(action); assertPermString("topic:my...
@Udf(description = "Subtracts a duration from a timestamp") public Timestamp timestampSub( @UdfParameter(description = "A unit of time, for example DAY or HOUR") final TimeUnit unit, @UdfParameter( description = "An integer number of intervals to subtract")final Integer interval, @UdfParam...
@Test public void subtractFromTimestampNegativeResult() { // When: final Timestamp result = udf.timestampSub(TimeUnit.MILLISECONDS, 300, new Timestamp(100)); // Then: final Timestamp expectedResult = new Timestamp(-200); assertThat(result, is(expectedResult)); }
@Override public boolean usesXAResource(final XAResource xaResource) { return resourceName.equals(((SingleXAResource) xaResource).getResourceName()); }
@Test void assertUseXAResource() { AtomikosXARecoverableResource atomikosXARecoverableResource = new AtomikosXARecoverableResource("ds1", xaDataSource); assertTrue(atomikosXARecoverableResource.usesXAResource(singleXAResource)); }
public static String uncompress(byte[] compressedURL) { StringBuffer url = new StringBuffer(); switch (compressedURL[0] & 0x0f) { case EDDYSTONE_URL_PROTOCOL_HTTP_WWW: url.append(URL_PROTOCOL_HTTP_WWW_DOT); break; case EDDYSTONE_URL_PROTOCOL_HTTPS_...
@Test public void testUncompressHttpsURL() { String testURL = "https://www.radiusnetworks.com"; byte[] testBytes = {0x01, 'r', 'a', 'd', 'i', 'u', 's', 'n', 'e', 't', 'w', 'o', 'r', 'k', 's', 0x07}; assertEquals(testURL, UrlBeaconUrlCompressor.uncompress(testBytes)); }
@ProcessElement public ProcessContinuation processElement( @Element PulsarSourceDescriptor pulsarSourceDescriptor, RestrictionTracker<OffsetRange, Long> tracker, WatermarkEstimator watermarkEstimator, OutputReceiver<PulsarMessage> output) throws IOException { long startTimestamp = tr...
@Test public void testProcessElementWhenHasReachedEndTopic() throws Exception { MockOutputReceiver receiver = new MockOutputReceiver(); fakePulsarReader.setReachedEndOfTopic(true); OffsetRangeTracker tracker = new OffsetRangeTracker(new OffsetRange(0L, Long.MAX_VALUE)); DoFn.ProcessContinuation result...
public void unionFields(Record other) { final int minFields = Math.min(this.numFields, other.numFields); final int maxFields = Math.max(this.numFields, other.numFields); final int[] offsets = this.offsets.length >= maxFields ? this.offsets : new int[maxFields]; final int[] lengths = thi...
@Test void testUnionFields() { final Value[][] values = new Value[][] { {new IntValue(56), null, new IntValue(-7628761)}, {null, new StringValue("Hello Test!"), null}, {null, null, null, null, null, null, null, null}, ...
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) { KafkaMetadataState currentState = metadataState; metadataState = switch (currentState) { case KRaft -> onKRaft(kafkaStatus); case ZooKeeper -> onZooKeeper(kafkaStatus); case KRaftMigration -...
@Test public void testWarningInKRaftDualWriting() { Kafka kafka = new KafkaBuilder(KAFKA) .editMetadata() .addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "enabled") .endMetadata() .withNewStatus() .withKafkaMetadata...
public static void checkArgument(boolean isValid, String message) throws IllegalArgumentException { if (!isValid) { throw new IllegalArgumentException(message); } }
@Test public void testCheckArgumentWithOneParam() { try { Preconditions.checkArgument(true, "Test message %s", 12); } catch (IllegalArgumentException e) { Assert.fail("Should not throw exception when isValid is true"); } try { Preconditions.checkArgument(false, "Test message %s", 12...
@Override public void close() { }
@Test public void shouldSucceed_removeRemoteNode() throws ExecutionException, InterruptedException { // Given: final AtomicReference<Set<KsqlNode>> nodes = new AtomicReference<>( ImmutableSet.of(ksqlNodeLocal, ksqlNodeRemote)); final PushRouting routing = new PushRouting(sqr -> nodes.get(), 50, tr...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof BridgeName) { final BridgeName that = (BridgeName) obj; return this.getClass() == that.getClass() && Objects.equals(this.name, that.name)...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(bridgeName1, sameAsBridgeName1) .addEqualityGroup(bridgeName2) .testEquals(); }
public String getProfileParams() { return get(JobContext.TASK_PROFILE_PARAMS, MRJobConfig.DEFAULT_TASK_PROFILE_PARAMS); }
@Test public void testProfileParamsDefaults() { JobConf configuration = new JobConf(); String result = configuration.getProfileParams(); Assert.assertNotNull(result); Assert.assertTrue(result.contains("file=%s")); Assert.assertTrue(result.startsWith("-agentlib:hprof")); }
@Nonnull public static <T> Traverser<T> traverseArray(@Nonnull T[] array) { return new ArrayTraverser<>(array); }
@Test public void when_traverseArray_then_seeAllItems() { validateTraversal(traverseArray(new Integer[] {1, 2})); }
public static ClusterOperatorConfig buildFromMap(Map<String, String> map) { warningsForRemovedEndVars(map); KafkaVersion.Lookup lookup = parseKafkaVersions(map.get(STRIMZI_KAFKA_IMAGES), map.get(STRIMZI_KAFKA_CONNECT_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER...
@Test public void testInvalidCustomResourceSelectorLabels() { Map<String, String> envVars = new HashMap<>(ClusterOperatorConfigTest.ENV_VARS); envVars.put(ClusterOperatorConfig.CUSTOM_RESOURCE_SELECTOR.key(), "nsLabelKey1,nsLabelKey2"); InvalidConfigurationException e = assertThrows(Invalid...
@Override protected boolean hasChildProjectsPermission(String permission, String applicationUuid) { return false; }
@Test public void hasChildProjectsPermission() { assertThat(githubWebhookUserSession.hasChildProjectsPermission("perm", "project")).isFalse(); }
@VisibleForTesting public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics) { if (rowCount == 0) { return Domain.none(type); } if (columnStatistics == null) { return Domain.all(type); } if (columnStatistics.hasN...
@Test public void testBigint() { assertEquals(getDomain(BIGINT, 0, null), Domain.none(BIGINT)); assertEquals(getDomain(BIGINT, 10, null), Domain.all(BIGINT)); assertEquals(getDomain(BIGINT, 0, integerColumnStats(null, null, null)), Domain.none(BIGINT)); assertEquals(getDomain(BI...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testTransactionalSplitBatchAndSend() throws Exception { ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(123456L, (short) 0); TopicPartition tp = new TopicPartition("testSplitBatchAndSend", 1); TransactionManager txnManager = new TransactionManager(logContext,...
@SuppressWarnings("unchecked") @Override public MoveApplicationAcrossQueuesResponse moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest request) throws YarnException { ApplicationId applicationId = request.getApplicationId(); UserGroupInformation callerUGI = getCallerUgi(applicationId, ...
@Test (expected = YarnException.class) public void testNonExistingQueue() throws Exception { ApplicationId applicationId = getApplicationId(1); UserGroupInformation aclUGI = UserGroupInformation.getCurrentUser(); QueueACLsManager queueAclsManager = getQueueAclManager(); ApplicationACLsManager appAclsM...
public static MetricsInfo info(String name, String description) { return Info.INSTANCE.cache.add(name, description); }
@Test public void testInfoOverflow() { MetricsInfo i0 = info("m0", "m desc"); for (int i = 0; i < MAX_INFO_NAMES + 1; ++i) { info("m"+ i, "m desc"); if (i < MAX_INFO_NAMES) { assertSame("m0 is still there", i0, info("m0", "m desc")); } } assertNotSame("m0 is gone", i0, info("m0...
@Override public void uploadAll(Configuration config) throws Exception { if (!config.get(KubernetesConfigOptions.LOCAL_UPLOAD_ENABLED)) { LOG.info( "Local artifact uploading is disabled. Set '{}' to enable.", KubernetesConfigOptions.LOCAL_UPLOAD_ENABLED.ke...
@Test void testUploadAllWithOneJobJar() throws Exception { File jar = getFlinkKubernetesJar(); String localUri = "local://" + jar.getAbsolutePath(); config.set(PipelineOptions.JARS, Collections.singletonList(localUri)); artifactUploader.uploadAll(config); assertJobJarUri(ja...
static String indent(String item) { // '([^']|'')*': Matches the escape sequence "'...'" where the content between "'" // characters can contain anything except "'" unless its doubled (''). // // Then each match is checked. If it starts with "'", it's left unchanged // (escaped ...
@Test void testIndentChildWithEscapedQuotes() { String sourceQuery = "SELECT *, '',\n'' FROM source_t"; String s = String.format( "SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery)); assertThat(s) .isEqualTo( ...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testQualifiedViewColumnResolution() { // it should be possible to qualify the column reference with the view name analyze("SELECT v1.a FROM v1"); analyze("SELECT s1.v1.a FROM s1.v1"); analyze("SELECT tpch.s1.v1.a FROM tpch.s1.v1"); }
@Override public void unsubscribe(URL url, NotifyListener listener) { if (url == null) { throw new IllegalArgumentException("unsubscribe url == null"); } if (listener == null) { throw new IllegalArgumentException("unsubscribe listener == null"); } if (...
@Test void testUnsubscribe() { // check parameters try { abstractRegistry.unsubscribe(testUrl, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } // check parameters try...
public KsqlConfig cloneWithPropertyOverwrite(final Map<String, ?> props) { final Map<String, Object> cloneProps = new HashMap<>(originals()); cloneProps.putAll(props); final Map<String, ConfigValue> streamConfigProps = buildStreamingConfig(getKsqlStreamConfigProps(), props); return new KsqlConf...
@Test public void shouldCloneWithKsqlPropertyOverwrite() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap( KsqlConfig.KSQL_SERVICE_ID_CONFIG, "test")); final KsqlConfig ksqlConfigClone = ksqlConfig.cloneWithPropertyOverwrite( Collections.singletonMap( KsqlCon...
@Override @Nullable protected HttpHost determineProxy(HttpHost target, HttpContext context) throws HttpException { for (Pattern nonProxyHostPattern : nonProxyHostPatterns) { if (nonProxyHostPattern.matcher(target.getHostName()).matches()) { return null; } ...
@Test void testHostWithEndWildcardIsMatched() throws Exception { assertThat(routePlanner.determineProxy(new HttpHost("192.168.52.94"), httpContext)).isNull(); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexSpec indexSpec = (IndexSpec) o; return Objects.equal(name, indexSpec.name); }
@Test void equalAnotherObject() { var spec3 = new IndexSpec() .setName("metadata.name"); assertThat(spec3.equals(new Object())).isFalse(); }
@Override public TransformResultMetadata getResultMetadata() { return _resultMetadata; }
@Test public void testArrayElementAtString() { Random rand = new Random(); int index = rand.nextInt(MAX_NUM_MULTI_VALUES); ExpressionContext expression = RequestContextUtils.getExpression( String.format("array_element_at_string(%s, %d)", STRING_MV_COLUMN, index + 1)); TransformFunction transfo...
@Override public void close() { if (ch.isOpen()) { ch.close(); } }
@Test public void testNegativeTtl() throws Exception { final DnsNameResolver resolver = newResolver().negativeTtl(10).build(); try { resolveNonExistentDomain(resolver); final int size = 10000; final List<UnknownHostException> exceptions = new ArrayList<UnknownHos...
public GetMetaDataResponseHeader getControllerMetaData( final String controllerAddress) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, RemotingCommandException, MQBrokerException { final RemotingCommand request = RemotingCommand.createReque...
@Test public void assertGetControllerMetaData() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); GetMetaDataResponseHeader responseHeader = new GetMetaDataResponseHeader(); responseHeader.setGroup(group); responseHeader.setIsLeader(true); ...
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) { return new DateTime(dateStr, dateFormat); }
@Test public void parseByDateTimeFormatterTest() { final DateTime parse = DateUtil.parse("2021-12-01", DatePattern.NORM_DATE_FORMATTER); assertEquals("2021-12-01 00:00:00", parse.toString()); }
@Nullable public byte[] getValue() { return mValue; }
@Test public void setValue_UINT32_BE_big() { final MutableData data = new MutableData(new byte[4]); data.setValue(0xF0000001L, Data.FORMAT_UINT32_BE, 0); assertArrayEquals(new byte[] { (byte) 0xF0, 0x00, 0x00, 0x01 } , data.getValue()); }
@Override public Num calculate(BarSeries series, Position position) { if (position.isClosed()) { Num loss = excludeCosts ? position.getGrossProfit() : position.getProfit(); return loss.isNegative() ? loss : series.zero(); } return series.zero(); }
@Test public void calculateComparingIncludingVsExcludingCosts() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); LinearTransactionCostModel transactionCost = new LinearTransactionCostModel(0.01); ZeroCostModel holdingCost = new ZeroCostModel(); Tradi...
public static LogMessage getInstance() { return new LogMessage(); }
@Test public void testGetInstanceShouldReturnANewLogMessageInstance() { final LogMessage newInstance = LogMessage.getInstance(); assertNotNull(newInstance); assertNotSame(logMessage, newInstance); }
public Object clone() { XMLOutputMeta retval = (XMLOutputMeta) super.clone(); int nrfields = outputFields.length; retval.allocate( nrfields ); for ( int i = 0; i < nrfields; i++ ) { retval.outputFields[i] = (XMLField) outputFields[i].clone(); } return retval; }
@Test public void testClone() throws Exception { XMLOutputMeta xmlOutputMeta = new XMLOutputMeta(); Node stepnode = getTestNode(); DatabaseMeta dbMeta = mock( DatabaseMeta.class ); IMetaStore metaStore = mock( IMetaStore.class ); xmlOutputMeta.loadXML( stepnode, Collections.singletonList( dbMeta )...
public final void containsKey(@Nullable Object key) { check("keySet()").that(checkNotNull(actual).keySet()).contains(key); }
@Test public void containsKeyNull() { Multimap<String, String> multimap = HashMultimap.create(); multimap.put(null, "null"); assertThat(multimap).containsKey(null); }
@Override public void run(Namespace namespace, Liquibase liquibase) throws Exception { final boolean list = firstNonNull(namespace.getBoolean("list"), false); final boolean release = firstNonNull(namespace.getBoolean("release"), false); if (list == release) { throw new IllegalAr...
@Test void testRelease() throws Exception { // We can't create locks in the database, so use mocks final Liquibase liquibase = Mockito.mock(Liquibase.class); locksCommand.run(new Namespace(Map.of("list", false, "release", true)), liquibase); Mockito.verify(liquibase).forceReleaseLock...
public static String evaluate(String jsonText, JsonEvaluationSpecification specification) throws JsonMappingException { // Parse json text ang get root node. JsonNode rootNode; try { ObjectMapper mapper = new ObjectMapper(); rootNode = mapper.readTree(new StringReader(jsonTe...
@Test void testEqualsOperatorDispatcher() throws Exception { DispatchCases cases = new DispatchCases(); Map<String, String> dispatchCases = new HashMap<>(); dispatchCases.put("Belgium", "OK"); dispatchCases.put("Germany", "KO"); dispatchCases.put("default", "Why not?"); cases.put...
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception { return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM); }
@Test public void testSuccess() throws Exception { Mockito.when(mockCallable.call()).thenReturn("success"); assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(100), 1, mockTime)); Mockito.verify(mockCallable, Mockito.times(1)).call(); }
@Override public TensorProto serialize() { TensorProto.Builder builder = TensorProto.newBuilder(); builder.setVersion(CURRENT_VERSION); builder.setClassName(DenseVector.class.getName()); DenseTensorProto.Builder dataBuilder = DenseTensorProto.newBuilder(); dataBuilder.addAl...
@Test public void serializationTest() { DenseVector a = generateVectorA(); TensorProto proto = a.serialize(); Tensor deser = Tensor.deserialize(proto); assertEquals(a,deser); }
public FactMapping addFactMapping(int index, FactMapping toClone) { FactMapping toReturn = toClone.cloneFactMapping(); factMappings.add(index, toReturn); return toReturn; }
@Test public void addFactMapping_byIndexAndFactMapping() { FactMapping toClone = new FactMapping(); toClone.setFactAlias("ALIAS"); toClone.setExpressionAlias("EXPRESSION_ALIAS"); final FactMapping cloned = modelDescriptor.addFactMapping(0, toClone); assertTh...
@Override public void run() { final Instant now = time.get(); try { final Collection<PersistentQueryMetadata> queries = engine.getPersistentQueries(); final Optional<Double> saturation = queries.stream() .collect(Collectors.groupingBy(PersistentQueryMetadata::getQueryApplicationId)) ...
@Test public void shouldComputeSaturationForQuery() { // Given: final Instant start = Instant.now(); when(clock.get()).thenReturn(start); givenMetrics(kafkaStreams1) .withThreadStartTime("t1", start.minus(WINDOW.multipliedBy(2))) .withBlockedTime("t1", Duration.ofMinutes(2)) .w...
void regionFinished(SchedulingPipelinedRegion region) { for (ConsumerRegionGroupExecutionView executionView : executionViewByRegion.getOrDefault(region, Collections.emptySet())) { executionView.regionFinished(region); } }
@Test void testRegionFinished() throws Exception { consumerRegionGroupExecutionViewMaintainer.regionFinished(consumerRegion); assertThat(consumerRegionGroupExecutionView.isFinished()).isTrue(); }
@Override public Object getServiceDetail(String namespaceId, String groupName, String serviceName) throws NacosException { Service service = Service.newService(namespaceId, groupName, serviceName); if (!ServiceManager.getInstance().containSingleton(service)) { throw new NacosException(Na...
@Test void testGetServiceDetail() throws NacosException { ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setProtectThreshold(0.75F); Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(serviceMetadata)); Mockito.when(servic...
@Override public boolean isValid(Link link, ResourceContext context) { // explicitly call a method not depending on LinkResourceService return isValid(link); }
@Test public void testMeteredAllowed() { MeteredConstraint constraint = new MeteredConstraint(true); assertThat(constraint.isValid(meteredLink, resourceContext), is(true)); assertThat(constraint.isValid(nonMeteredLink, resourceContext), is(true)); assertThat(constraint.isValid(unAnn...
@NonNull @Override public EncodeStrategy getEncodeStrategy(@NonNull Options options) { Boolean encodeTransformation = options.get(ENCODE_TRANSFORMATION); return encodeTransformation != null && encodeTransformation ? EncodeStrategy.TRANSFORMED : EncodeStrategy.SOURCE; }
@Test public void testEncodeStrategy_withEncodeTransformationFalse_returnsSource() { options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, false); assertThat(encoder.getEncodeStrategy(options)).isEqualTo(EncodeStrategy.SOURCE); }
@Nonnull @Override public Optional<? extends INode> parse( @Nullable final String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } for (IMapper mapper : jcaSpecificAlgorithmMappers) { Optional<? extend...
@Test void blockCipher() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaAlgorithmMapper jcaAlgorithmMapper = new JcaAlgorithmMapper(); Optional<? extends INode> assetOptional = jcaAlgorith...
@VisibleForTesting public String validateMobile(String mobile) { if (StrUtil.isEmpty(mobile)) { throw exception(SMS_SEND_MOBILE_NOT_EXISTS); } return mobile; }
@Test public void testCheckMobile_notExists() { // 准备参数 // mock 方法 // 调用,并断言异常 assertServiceException(() -> smsSendService.validateMobile(null), SMS_SEND_MOBILE_NOT_EXISTS); }
public static <I> Builder<I> foreach(Iterable<I> items) { return new Builder<>(requireNonNull(items, "items")); }
@Test public void testFailNoStoppingSuppressed() throws Throwable { assertFailed(builder().suppressExceptions(), failingTask); failingTask.assertInvoked("Continued through operations", ITEM_COUNT); items.forEach(Item::assertCommittedOrFailed); }
public String getCustomError(HttpRequestWrapper req, HttpResponseWrapper res) { for (MatcherAndError m : matchersAndLogs) { if (m.getMatcher().matchResponse(req, res)) { return m.getCustomError().customError(req, res); } } return null; }
@Test public void testMatchesCodeAndUrlContains() throws IOException { HttpRequestWrapper request = createHttpRequest(BQ_TABLES_LIST_URL); HttpResponseWrapper response = createHttpResponse(403); CustomHttpErrors.Builder builder = new CustomHttpErrors.Builder(); builder.addErrorForCodeAndUrlContains(4...
@Override protected TableRecords getUndoRows() { return sqlUndoLog.getAfterImage(); }
@Test public void getUndoRows() { Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getAfterImage()); }
ControllerResult<Map<String, ApiError>> updateFeatures( Map<String, Short> updates, Map<String, FeatureUpdate.UpgradeType> upgradeTypes, boolean validateOnly ) { TreeMap<String, ApiError> results = new TreeMap<>(); List<ApiMessageAndVersion> records = BoundedL...
@Disabled @Test public void testCanUseUnsafeDowngradeIfMetadataChanged() { FeatureControlManager manager = TEST_MANAGER_BUILDER1.build(); assertEquals(ControllerResult.of(Collections.emptyList(), singletonMap(MetadataVersion.FEATURE_NAME, ApiError.NONE)), ...
public StringAppender append(final String message) { if(StringUtils.isBlank(StringUtils.trim(message))) { return this; } if(buffer.length() > 0) { buffer.append(" "); } buffer.append(StringUtils.trim(message)); if(buffer.charAt(buffer.length() - 1)...
@Test public void testAppend() { assertEquals("Verification Code.", new StringAppender().append("Verification Code:").toString()); assertEquals("Message.", new StringAppender().append("Message").toString()); assertEquals("Message.", new StringAppender().append("Message.").toString()); ...
@Nonnull public static <K, V> Sink<Entry<K, V>> map(@Nonnull String mapName) { return map(mapName, Entry::getKey, Entry::getValue); }
@Test @SuppressWarnings("unchecked") public void test_adaptingPartitionFunction() { Pipeline p = Pipeline.create(); StreamStage<KeyedWindowResult<String, Long>> input1 = p.readFrom(TestSources.items(0)) .addTimestamps(i -> i, 0) .groupingKey(item...
@CanIgnoreReturnValue public final Ordered containsExactly() { return containsExactlyEntriesIn(ImmutableMap.of()); }
@Test public void containsExactlyExtraKeyAndMissingKey() { ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "march", 3); expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "feb", 2); assertFailureKeys( "missing keys", "for key", "expected value", ...
public List<List<String>> getAllInfo(String dictionaryName) throws Exception { List<List<String>> allInfo = Lists.newArrayList(); lock.lock(); try { for (Map.Entry<Long, Dictionary> entry : dictionariesMapById.entrySet()) { Dictionary dictionary = entry.getValue(); ...
@Test public void testShowDictionary() throws Exception { dictionaryMgr.getAllInfo("dict"); }
public static UUnary create(Kind unaryOp, UExpression expression) { checkArgument( UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp); return new AutoValue_UUnary(unaryOp, expression); }
@Test public void postDecrement() { assertUnifiesAndInlines("foo--", UUnary.create(Kind.POSTFIX_DECREMENT, fooIdent)); }
public static boolean isIpV6Endpoint(NetworkEndpoint networkEndpoint) { return hasIpAddress(networkEndpoint) && networkEndpoint.getIpAddress().getAddressFamily().equals(AddressFamily.IPV6); }
@Test public void isIpV6Endpoint_withIpV4Endpoint_returnsFalse() { NetworkEndpoint ipV4Endpoint = NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.IP) .setIpAddress( IpAddress.newBuilder().setAddress("1.2.3.4").setAddressFamily(AddressFamily.IPV4)) ...
public static String toShortString(Object obj) { if (obj == null) { return "null"; } return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); }
@Test void testToShortString() { assertThat(ClassUtils.toShortString(null), equalTo("null")); assertThat(ClassUtils.toShortString(new ClassUtilsTest()), startsWith("ClassUtilsTest@")); }
public void setFilePaths(String... filePaths) { Path[] paths = new Path[filePaths.length]; for (int i = 0; i < paths.length; i++) { paths[i] = new Path(filePaths[i]); } setFilePaths(paths); }
@Test void testSetPathsOnePathNull() { assertThatThrownBy( () -> new MultiDummyFileInputFormat() .setFilePaths("/an/imaginary/path", null)) .isInstanceOf(IllegalArgumentException.class); }
public List<ServiceInstance> findAllNonRunningInstances() { return jdbcRepository.getDslContextWrapper().transactionResult( configuration -> findAllNonRunningInstances(configuration, false) ); }
@Test protected void shouldFindAllNonRunningInstances() { // Given AbstractJdbcServiceInstanceRepositoryTest.Fixtures.all().forEach(repository::save); // When List<ServiceInstance> results = repository.findAllNonRunningInstances(); // Then assertEquals(AbstractJdbcS...
public ShowResultSet modifyBackendProperty(ModifyBackendClause modifyBackendClause) throws DdlException { String backendHostPort = modifyBackendClause.getBackendHostPort(); Map<String, String> properties = modifyBackendClause.getProperties(); // check backend existence Backend backend =...
@Test public void testModifyBackendProperty() throws DdlException { Backend be = new Backend(100, "originalHost", 1000); service.addBackend(be); Map<String, String> properties = Maps.newHashMap(); String location = "rack:rack1"; properties.put(AlterSystemStmtAnalyzer.PROP_KEY...
@Override public Address translate(Address address) throws Exception { if (address == null) { return null; } // if it is inside cloud, return private address otherwise we need to translate it. if (!usePublic) { return address; } Address publi...
@Test public void testTranslate() throws Exception { Address privateAddress = new Address("10.0.0.1", 5701); Address publicAddress = new Address("198.51.100.1", 5701); RemoteAddressProvider provider = new RemoteAddressProvider(() -> Collections.singletonMap(privateAddress, publicAddress), ...
public static Object convertBigDecimalValue(final Object value, final boolean needScale, final int scale) { if (null == value) { return convertNullValue(BigDecimal.class); } if (BigDecimal.class == value.getClass()) { return adjustBigDecimalResult((BigDecimal) value, need...
@Test void assertConvertBigDecimalValue() { BigDecimal bigDecimal = (BigDecimal) ResultSetUtils.convertBigDecimalValue("12", false, 0); assertThat(bigDecimal, is(BigDecimal.valueOf(12L))); }
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine) { return scanArtifacts(project, engine, false); }
@Test public void testScanArtifacts() throws DatabaseException, InvalidSettingException { new MockUp<MavenProject>() { @Mock public Set<Artifact> getArtifacts() { Set<Artifact> artifacts = new HashSet<>(); Artifact a = new ArtifactStub(); ...
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testMissedMatchWithEqualValues() { StreamRule rule = getSampleRule(); rule.setValue("-9001"); Message msg = getSampleMessage(); msg.addField("something", "-9001"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule));...
@ApiOperation(value = "Get column info for a single table", tags = { "Database tables" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the table exists and the table column info is returned."), @ApiResponse(code = 404, message = "Indicates the requested table does no...
@Test public void testGetTableColumns() throws Exception { String tableName = managementService.getTableCount().keySet().iterator().next(); TableMetaData metaData = managementService.getTableMetaData(tableName); CloseableHttpResponse response = executeRequest( new HttpGet(S...
public static boolean unblock( final UnsafeBuffer[] termBuffers, final UnsafeBuffer logMetaDataBuffer, final long blockedPosition, final int termLength) { final int positionBitsToShift = LogBufferDescriptor.positionBitsToShift(termLength); final int blockedTermCount =...
@Test void shouldUnblockWhenPositionHasNonCommittedMessageAndTailPastEndOfTerm() { final int messageLength = HEADER_LENGTH * 4; final int blockedOffset = TERM_LENGTH - messageLength; final long blockedPosition = computePosition(TERM_ID_1, blockedOffset, positionBitsToShift, TERM_ID_1); ...
public DomainWildcardMappingBuilder<V> add(String hostname, V output) { map.put(normalizeHostName(hostname), checkNotNull(output, "output")); return this; }
@Test public void testNullDomainNamePatternsAreForbidden() { assertThrows(NullPointerException.class, new Executable() { @Override public void execute() { new DomainWildcardMappingBuilder<String>("NotFound").add(null, "Some value"); } }); }
public XmlStreamInfo information() throws IOException { if (information.problem != null) { return information; } if (XMLStreamConstants.START_DOCUMENT != reader.getEventType()) { information.problem = new IllegalStateException("Expected START_DOCUMENT"); retu...
@Test public void documentFullOfNamespaces() throws IOException { String xml = readAllFromFile("documentFullOfNamespaces.xml"); XmlStreamDetector detector = new XmlStreamDetector(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); XmlStreamInfo info = detector.i...
@Override public void setRampUpPercent(long rampUpPercent) { Validate.isTrue((rampUpPercent >= 0) && (rampUpPercent <= 100), "rampUpPercent must be a value between 0 and 100"); this.rampUpPercent = rampUpPercent; }
@Test(expected = IllegalArgumentException.class) public void testSetRampUpPercent_exceeds100() { sampler.setRampUpPercent(101); }
public boolean registerAndBootstrapService() { try { client.registerService("starrocks"); } catch (StarClientException e) { if (e.getCode() != StatusCode.ALREADY_EXIST) { LOG.error("Failed to register service from starMgr. Error: {}", e); return fa...
@Test public void testRegisterServiceException() throws Exception { new Expectations() { { client.registerService(SERVICE_NAME); minTimes = 0; result = new StarClientException(StatusCode.ALREADY_EXIST, "service already exist...
@SuppressWarnings("unchecked") // visible for testing public StitchRequestBody createStitchRequestBody(final Message inMessage) { if (inMessage.getBody() instanceof StitchRequestBody) { return createStitchRequestBodyFromStitchRequestBody(inMessage.getBody(StitchRequestBody.class), inMessage)...
@Test void testIfCreateFromIterable() { final StitchConfiguration configuration = new StitchConfiguration(); configuration.setTableName("table_1"); configuration.setStitchSchema(StitchSchema.builder().addKeyword("field_1", "string").build()); configuration.setKeyNames("field_1"); ...
public List<T> topologicalSort() throws CyclicDependencyException { long stamp = lock.readLock(); try { ArrayList<T> result = new ArrayList<>(); Deque<T> noIncomingEdges = new ArrayDeque<>(); Map<T, Integer> temp = new HashMap<>(); for (Map.Entry<T, Set<T>> incoming : in...
@Test public void testConcurrentAccess() throws Exception { DependencyGraph<String> graph = new DependencyGraph<>(); ExecutorService service = Executors.newCachedThreadPool(getTestThreadFactory("Worker")); try { CountDownLatch startLatch = new CountDownLatch(1); int threads = 20; ...
public final int readInt() throws IOException { if (input instanceof RandomAccessFile) { return ((RandomAccessFile) input).readInt(); } else if (input instanceof DataInputStream) { return ((DataInputStream) input).readInt(); } else { throw new UnsupportedOpera...
@Test public void testReadInt() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(65537, inStream.readInt()); // first int HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, ...
static IDXData readData(Path path) throws IOException { InputStream inputStream = IOUtil.getInputStreamForLocation(path.toString()); if (inputStream == null) { throw new FileNotFoundException("Failed to load from path - " + path); } // DataInputStream.close implicitly closes ...
@Test public void testInvalidIDX() throws URISyntaxException { Path dataFile = Paths.get(IDXDataSourceTest.class.getResource("/org/tribuo/datasource/too-much-data.idx").toURI()); assertThrows(IllegalStateException.class, () -> IDXDataSource.readData(dataFile)); Path otherDataFile = Paths.get...
@Override public void execute(final ConnectionSession connectionSession) { mergedResult = new LocalDataMergedResult(Collections.singleton(new LocalDataQueryResultRow( DatabaseProtocolServerInfo.getProtocolVersion(connectionSession.getUsedDatabaseName(), TypedSPILoader.getService(DatabaseType...
@Test void assertExecuteWithAlias() throws SQLException { SelectStatement selectStatement = mock(SelectStatement.class); when(selectStatement.getProjections()).thenReturn(createProjectionsSegmentWithAlias()); ShowVersionExecutor executor = new ShowVersionExecutor(selectStatement); ex...
void addAnalyticHeaders(List<Header> headers) { headers.add(new RecordHeader("_producerId", getClientId().getBytes(StandardCharsets.UTF_8))); headers.add(new RecordHeader("_threadName", Thread.currentThread().getName().getBytes(StandardCharsets.UTF_8))); if (log.isTraceEnabled()) { t...
@Test void testAddAnalyticHeaders() { List<Header> headers = new ArrayList<>(); producerTemplate.addAnalyticHeaders(headers); assertThat(headers).isNotEmpty(); headers.forEach(r -> log.info("RecordHeader key [{}] value [{}]", r.key(), new String(r.value(), StandardCharsets.UTF_8))); ...
@Override public HttpRestResult<String> httpPost(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception { final long endTime = System.currentTimeMillis() + readTimeoutMs; String currentServerAddr = serverListMgr.getC...
@Test void testRetryPostWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenThrow(new ConnectExceptio...
public static StatTriggerInstruction statTrigger(Map<StatTriggerField, Long> statTriggerMap, StatTriggerFlag flag) { checkNotNull(statTriggerMap, "Stat trigger map cannot be null"); checkNotNull(flag, "Stat trigger flag cannot be null"); retu...
@Test public void testStatTriggerTrafficMethod() { final Instruction instruction = Instructions.statTrigger(statTriggerFieldMap1, flag1); final Instructions.StatTriggerInstruction statTriggerInstruction = checkAndConvert(instruction, Instruction.Type.STAT_TRIG...
void shutdown(@Observes ShutdownEvent event) { if (jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) { backgroundJobServerInstance.get().stop(); } if (jobRunrBuildTimeConfiguration.dashboard().enabled()) { dashboardWebServerInstance.get().stop(); } ...
@Test void jobRunrStarterStopsDashboardIfConfigured() { when(dashboardConfiguration.enabled()).thenReturn(true); jobRunrStarter.shutdown(new ShutdownEvent()); verify(dashboardWebServer).stop(); }
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void retryOnResultUsingObservable() throws InterruptedException { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of("testName", config...
public synchronized void executeDdlStatement(String statement) throws IllegalStateException { checkIsUsable(); maybeCreateInstance(); maybeCreateDatabase(); LOG.info("Executing DDL statement '{}' on database {}.", statement, databaseId); try { databaseAdminClient .updateDatabaseDdl(...
@Test public void testExecuteDdlStatementShouldThrowExceptionWhenSpannerCreateInstanceFails() throws ExecutionException, InterruptedException { // arrange when(spanner.getInstanceAdminClient().createInstance(any()).get()) .thenThrow(InterruptedException.class); prepareCreateDatabaseMock(); ...
static Optional<VespaVersion> getVespaVersion() { return Optional.of(getCompiledVespaVersion()); }
@Test public void testVespaVersion() { assertThat(JRTConfigRequestFactory.getVespaVersion().get(), is(defaultVespaVersion)); }
@Override public String toString() { return String.format("The giant looks %s, %s and %s.", health, fatigue, nourishment); }
@Test void testSetNourishment() { final var model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); assertEquals(Nourishment.SATURATED, model.getNourishment()); var messageFormat = "The giant looks healthy, alert and %s."; for (final var nourishment : Nourishment.values()) { ...
@JsonProperty("isBase64Encoded") public boolean isBase64Encoded() { return isBase64Encoded; }
@Test void deserialize_base64Encoded_readsBoolCorrectly() throws IOException { AwsProxyRequest req = new AwsProxyRequestBuilder() .fromJsonString(getRequestJson(true, CUSTOM_HEADER_KEY_LOWER_CASE, CUSTOM_HEADER_VALUE)).build(); assertTrue(req.isBase64Encoded()); req = new Aws...
public static <EventT> Write<EventT> write() { return new AutoValue_JmsIO_Write.Builder<EventT>().build(); }
@Test public void testWriteDynamicMessage() throws Exception { Connection connection = connectionFactory.createConnection(USERNAME, PASSWORD); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumerOne = session.createConsumer(session.c...
@Override public InputStream getBody() throws IOException { return response.getEntity().getContent(); }
@Test void testGetBody() throws IOException { assertEquals(inputStream, clientHttpResponse.getBody()); }
public void print(final ByteBuffer encodedMessage, final StringBuilder output) { final UnsafeBuffer buffer = new UnsafeBuffer(encodedMessage); print(output, buffer, 0); }
@Test public void exampleVarData() throws Exception { final ByteBuffer encodedSchemaBuffer = ByteBuffer.allocate(SCHEMA_BUFFER_CAPACITY); encodeSchema(encodedSchemaBuffer); final ByteBuffer encodedMsgBuffer = ByteBuffer.allocate(MSG_BUFFER_CAPACITY); final UnsafeBuffer buffer = ...
public void updateAutoCommitTimer(final long currentTimeMs) { this.autoCommitState.ifPresent(t -> t.updateTimer(currentTimeMs)); }
@Test public void testAutocommitInterceptorsNotInvokedOnError() { TopicPartition t1p = new TopicPartition("topic1", 0); subscriptionState.assignFromUser(singleton(t1p)); subscriptionState.seek(t1p, 100); CommitRequestManager commitRequestManager = create(true, 100); time.sle...
@Override public boolean setProperties(Namespace namespace, Map<String, String> properties) throws NoSuchNamespaceException { Map<String, String> newProperties = Maps.newHashMap(); newProperties.putAll(loadNamespaceMetadata(namespace)); newProperties.putAll(properties); glue.updateDatabase( ...
@Test public void testSetProperties() { Map<String, String> parameters = Maps.newHashMap(); parameters.put("key", "val"); Mockito.doReturn( GetDatabaseResponse.builder() .database(Database.builder().name("db1").parameters(parameters).build()) .build()) ....
@Override public void updateDemand() { // Compute demand by iterating through apps in the queue // Limit demand to maxResources Resource tmpDemand = Resources.createResource(0); readLock.lock(); try { for (FSAppAttempt sched : runnableApps) { sched.updateDemand(); Resources.a...
@Test public void testUpdateDemand() { conf.set(FairSchedulerConfiguration.ASSIGN_MULTIPLE, "false"); resourceManager = new MockRM(conf); resourceManager.start(); scheduler = (FairScheduler) resourceManager.getResourceScheduler(); String queueName = "root.queue1"; FSLeafQueue schedulable = ne...
@Override public List<?> deserialize(final String topic, final byte[] bytes) { if (bytes == null) { return null; } try { final String recordCsvString = new String(bytes, StandardCharsets.UTF_8); final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat) .ge...
@Test public void shouldDeserializeDelimitedCorrectlyWithTabDelimiter() { // Given: final byte[] bytes = "1511897796092\t1\titem_1\t10.0\t10.10\t100\t10\t100\tew==\r\n" .getBytes(StandardCharsets.UTF_8); final KsqlDelimitedDeserializer deserializer = new KsqlDelimitedDeserializer(ORDER_SC...
@Override public Set<Class<? extends BaseStepMeta>> getSupportedSteps() { return new HashSet<Class<? extends BaseStepMeta>>() { { add( XMLOutputMeta.class ); } }; }
@Test public void testGetSupportedSteps() { XMLOutputStepAnalyzer analyzer = new XMLOutputStepAnalyzer(); Set<Class<? extends BaseStepMeta>> types = analyzer.getSupportedSteps(); assertNotNull( types ); assertEquals( types.size(), 1 ); assertTrue( types.contains( XMLOutputMeta.class ) ); }
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertCompressedStreamMessageToAmqpMessageWithAmqpValueBody() throws Exception { ActiveMQStreamMessage outbound = createStreamMessage(true); outbound.writeBoolean(false); outbound.writeString("test"); outbound.onSend(); outbound.storeContent(); ...
public static boolean isContentType(String contentType, Message message) { if (contentType == null) { return message.getContentType() == null; } else { return contentType.equals(message.getContentType()); } }
@Test public void testIsContentTypeWithNullStringValueAndNullMessageContentType() { Message message = Proton.message(); assertTrue(AmqpMessageSupport.isContentType(null, message)); }
@Override protected Release findLatestActiveRelease(String configAppId, String configClusterName, String configNamespace, ApolloNotificationMessages clientMessages) { return releaseService.findLatestActiveRelease(configAppId, configClusterName, configNamespace);...
@Test public void testLoadConfigWithDefaultClusterWithNoDataCenterRelease() throws Exception { when(releaseService.findLatestActiveRelease(someConfigAppId, someDataCenter, defaultNamespaceName)) .thenReturn(null); when(releaseService.findLatestActiveRelease(someConfigAppId, defaultClusterName, default...
@SuppressWarnings("unchecked") @Override public Result execute(Query query, Target target) { Query adjustedQuery = adjustQuery(query); switch (target.mode()) { case ALL_NODES: adjustedQuery = Query.of(adjustedQuery).partitionIdSet(getAllPartitionIds()).build(); ...
@Test public void runQueryOnAllPartitions_value() { Predicate<Object, Object> predicate = Predicates.equal("this", value); Query query = Query.of().mapName(map.getName()).predicate(predicate).iterationType(VALUE).build(); QueryResult result = queryEngine.execute(query, Target.ALL_NODES); ...