focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean equals(Object obj) { if (obj instanceof IdEntityResponse) { IdEntityResponse<?, ?> that = (IdEntityResponse<?, ?>) obj; return super.equals(that) && (this._entity == null ? that._entity == null : this._entity.equals(that._entity)); } else { re...
@Test public void testEquals() { IdEntityResponse<Long, AnyRecord> longIdEntityResponse1 = new IdEntityResponse<>(1L, new AnyRecord()); IdEntityResponse<Long, AnyRecord> longIdEntityResponse2 = new IdEntityResponse<>(1L, new AnyRecord()); IdEntityResponse<Long, AnyRecord> nullLongResponse = new IdEntity...
@Override public Credentials configure(final Host host) { final Credentials credentials = new Credentials(host.getCredentials()); final String profile = credentials.getUsername(); final Optional<Map.Entry<String, BasicProfile>> optional = profiles.entrySet().stream().filter(new Predicate<Map...
@Test public void testConfigure() throws Exception { new S3CredentialsConfigurator(new DisabledX509TrustManager(), new DefaultX509KeyManager(), new DisabledPasswordCallback()) .reload().configure(new Host(new TestProtocol())); }
public static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName) { Preconditions.checkNotNull(value, "Property '" + propertyName + "' cannot be null"); Preconditions.checkArgument( !value.trim().isEmpty(), "Property '" + propertyName + "' cannot be an empty string"); }
@Test public void testCheckNotNullAndNotEmpty_stringFailNull() { try { Validator.checkNotNullAndNotEmpty((String) null, "test"); Assert.fail(); } catch (NullPointerException npe) { Assert.assertEquals("Property 'test' cannot be null", npe.getMessage()); } }
@ApiOperation(value = "Get Customer Entity Views (getCustomerEntityViews)", notes = "Returns a page of Entity View objects assigned to customer. " + PAGE_DATA_PARAMETERS + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @R...
@Test public void testGetCustomerEntityViews() throws Exception { Customer customer = doPost("/api/customer", getNewCustomer("Test customer"), Customer.class); CustomerId customerId = customer.getId(); String urlTemplate = "/api/customer/" + customerId.getId().toString() + "/entityViewInfos?...
public static TopicPublishInfo topicRouteData2TopicPublishInfo(final String topic, final TopicRouteData route) { TopicPublishInfo info = new TopicPublishInfo(); // TO DO should check the usage of raw route, it is better to remove such field info.setTopicRouteData(route); if (route.getOrd...
@Test public void testTopicRouteData2TopicPublishInfoWithTopicQueueMappingByBroker() { TopicRouteData topicRouteData = createTopicRouteData(); when(topicRouteData.getTopicQueueMappingByBroker()).thenReturn(Collections.singletonMap(topic, new TopicQueueMappingInfo())); TopicPublishInfo actual...
public static Sensor punctuateSensor(final String threadId, final String taskId, final StreamsMetricsImpl streamsMetrics) { return invocationRateAndCountAndAvgAndMaxLatencySensor( threadId, taskId, ...
@Test public void shouldGetPunctuateSensor() { final String operation = "punctuate"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)) .thenReturn(expectedSensor); final String operationLatency = operation + StreamsMetricsImpl.LATENCY_S...
public void checkExecutePrerequisites(final ExecutionContext executionContext) { ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext))); }
@Test void assertCheckExecutePrerequisitesWhenExecuteDDLInPostgreSQLTransaction() { when(transactionRule.getDefaultType()).thenReturn(TransactionType.LOCAL); ExecutionContext executionContext = new ExecutionContext( new QueryContext(createPostgreSQLCreateTableStatementContext(), "", ...
public int getSeconds(HazelcastProperty property) { TimeUnit timeUnit = property.getTimeUnit(); return (int) timeUnit.toSeconds(getLong(property)); }
@Test public void getTimeUnit() { config.setProperty(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(), "300"); HazelcastProperties properties = new HazelcastProperties(config); assertEquals(300, properties.getSeconds(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL)); }
public static ParameterizedType parameterize(final Class<?> raw, final Type... typeArguments) { checkParameterizeMethodParameter(raw, typeArguments); return new ParameterizedTypeImpl(raw, raw.getEnclosingClass(), typeArguments); }
@Test void parameterize() { ParameterizedType stringComparableType = TypeUtils.parameterize(List.class, String.class); assertEquals("java.util.List<java.lang.String>", stringComparableType.toString()); assertEquals(List.class, stringComparableType.getRawType()); assertNull(stringComp...
@Override public void onOpened() { digestNotification(); }
@Test public void onOpened_appVisible_clearNotificationsDrawer() throws Exception { verify(mNotificationManager, never()).cancelAll(); setUpForegroundApp(); final PushNotification uut = createUUT(); uut.onOpened(); verify(mNotificationManager, never()).cancelAll(); }
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("x="); stringBuilder.append(this.x); stringBuilder.append(", y="); stringBuilder.append(this.y); return stringBuilder.toString(); }
@Test public void toStringTest() { Point point = new Point(1, 2); Assert.assertEquals(POINT_TO_STRING, point.toString()); }
public void setActiveParamChecker(String activeParamChecker) { this.activeParamChecker = activeParamChecker; }
@Test void setActiveParamChecker() { ServerParamCheckConfig paramCheckConfig = ServerParamCheckConfig.getInstance(); paramCheckConfig.setActiveParamChecker("test"); assertEquals("test", paramCheckConfig.getActiveParamChecker()); }
@Beta public static Application fromBuilder(Builder builder) throws Exception { return builder.build(); }
@Test void handler() throws Exception { try ( ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container() .handler("http://*/", MockHttpHandler.class)))) ) { ...
@Override public boolean replace(long key, long oldValue, long newValue) { assert oldValue != nullValue : "replace() called with null-sentinel oldValue " + nullValue; assert newValue != nullValue : "replace() called with null-sentinel newValue " + nullValue; final long valueAddr = hsa.get(key); ...
@Test(expected = AssertionError.class) @RequireAssertEnabled public void test_replaceIfEquals_invalidOldValue() { map.replace(newKey(), MISSING_VALUE, newValue()); }
protected String parseSubClusterId(CommandLine cliParser) { // If YARN Federation mode is not enabled, return empty. if (!isYarnFederationEnabled(getConf())) { return StringUtils.EMPTY; } String subClusterId = cliParser.getOptionValue(OPTION_SUBCLUSTERID); if (StringUtils.isBlank(subClusterId...
@Test public void testParseSubClusterId() throws Exception { rmAdminCLI.getConf().setBoolean(YarnConfiguration.FEDERATION_ENABLED, true); // replaceLabelsOnNode String[] replaceLabelsOnNodeArgs = {"-replaceLabelsOnNode", "node1:8000,x node2:8000=y node3,x node4=Y", "-subClusterId", "SC-1"}; a...
public final void contains(@Nullable Object element) { if (!Iterables.contains(checkNotNull(actual), element)) { List<@Nullable Object> elementList = newArrayList(element); if (hasMatchingToStringPair(actual, elementList)) { failWithoutActual( fact("expected to contain", element), ...
@Test public void iterableContainsFailsWithSameToString() { expectFailureWhenTestingThat(asList(1L, 2L, 3L, 2L)).contains(2); assertFailureKeys( "expected to contain", "an instance of", "but did not", "though it did contain", "full contents"); assertFailureValue("ex...
static void maybeReportHybridDiscoveryIssue(PluginDiscoveryMode discoveryMode, PluginScanResult serviceLoadingScanResult, PluginScanResult mergedResult) { SortedSet<PluginDesc<?>> missingPlugins = new TreeSet<>(); mergedResult.forEach(missingPlugins::add); serviceLoadingScanResult.forEach(missin...
@Test public void testServiceLoadWithPlugins() { try (LogCaptureAppender logCaptureAppender = LogCaptureAppender.createAndRegister(Plugins.class)) { Plugins.maybeReportHybridDiscoveryIssue(PluginDiscoveryMode.SERVICE_LOAD, nonEmpty, nonEmpty); assertTrue(logCaptureAppender.getEvents(...
public <E extends Enum> E getEnum(HazelcastProperty property, Class<E> enumClazz) { String value = getString(property); for (E enumConstant : enumClazz.getEnumConstants()) { if (equalsIgnoreCase(enumConstant.name(), value)) { return enumConstant; } } ...
@Test public void getEnum_default() { HazelcastProperties properties = new HazelcastProperties(config.getProperties()); HealthMonitorLevel healthMonitorLevel = properties .getEnum(ClusterProperty.HEALTH_MONITORING_LEVEL, HealthMonitorLevel.class); assertEquals(HealthMonitorL...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithOffsetDateTime() throws SQLException { OffsetDateTime result = OffsetDateTime.now(); when(mergeResultSet.getValue(1, Timestamp.class)).thenReturn(result); assertThat(shardingSphereResultSet.getObject(1, OffsetDateTime.class), is(result)); }
public static void extractFiles(File archive, File extractTo) throws ExtractionException { extractFiles(archive, extractTo, null); }
@Test(expected = org.owasp.dependencycheck.utils.ExtractionException.class) public void testExtractFiles_File_File() throws Exception { File destination = getSettings().getTempDirectory(); File archive = BaseTest.getResourceAsFile(this, "evil.zip"); ExtractionUtil.extractFiles(archive, desti...
@Override public boolean equals(Object other) { if (other instanceof Cost) { return equals((RelOptCost) other); } return false; }
@Test public void testEquals() { CostFactory factory = CostFactory.INSTANCE; checkEquals(factory.makeCost(1.0d, 2.0d, 3.0d), factory.makeCost(1.0d, 2.0d, 3.0d), true); checkEquals(factory.makeCost(1.0d, 2.0d, 3.0d), factory.makeCost(10.0d, 2.0d, 3.0d), false); checkEquals(factory....
public static StepRuntimeState retrieveStepRuntimeState( Map<String, Object> data, ObjectMapper objectMapper) { Object runtimeSummary = data.getOrDefault(Constants.STEP_RUNTIME_SUMMARY_FIELD, Collections.emptyMap()); if (runtimeSummary instanceof StepRuntimeSummary) { return ((StepRuntimeSum...
@Test public void testRetrieveStepRuntimeStateNotExists() { StepRuntimeState expected = new StepRuntimeState(); Assert.assertEquals( expected, StepHelper.retrieveStepRuntimeState( singletonMap(Constants.STEP_RUNTIME_SUMMARY_FIELD, Collections.emptyMap()), MAPPER)); }
@SuppressWarnings("deprecation") public static String toString(final Object obj) { if (obj == null) { return "null"; } //region Convert simple types to String directly if (obj instanceof CharSequence) { return "\"" + obj + "\""; } if (obj ins...
@Test void testToStringAndCycleDependency() throws Exception { //case: String Assertions.assertEquals("\"aaa\"", StringUtils.toString("aaa")); //case: CharSequence Assertions.assertEquals("\"bbb\"", StringUtils.toString(new StringBuilder("bbb"))); //case: Number Asse...
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 testMergeDifferentTransformFunctionConfig() { SinkConfig sinkConfig = createSinkConfig(); String newFunctionConfig = "{\"new-key\": \"new-value\"}"; SinkConfig newSinkConfig = createUpdatedSinkConfig("transformFunctionConfig", newFunctionConfig); SinkConfig mergedCo...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType; String colName; B...
@Test public void testAggregateSingleStat() throws MetaException { List<String> partitions = Collections.singletonList("part1"); ColumnStatisticsData data1 = new ColStatsBuilder<>(Boolean.class).numNulls(1).numFalses(2).numTrues(13).build(); List<ColStatsObjWithSourceInfo> statsList = Collections...
public String computeIfAbsent(String key, Function<String, String> function) { String value = cache.get(key); // value might be empty here! // empty value from config center will be cached here if (value == null) { // lock free, tolerate repeat apply, will return previous val...
@Test void test() { ConfigurationCache configurationCache = new ConfigurationCache(); String value = configurationCache.computeIfAbsent("k1", k -> "v1"); Assertions.assertEquals(value, "v1"); value = configurationCache.computeIfAbsent("k1", k -> "v2"); Assertions.assertEquals...
private int unconsumedBytes(Http2Stream stream) { return flowController().unconsumedBytes(stream); }
@Test public void errorDuringDeliveryShouldReturnCorrectNumberOfBytes() throws Exception { final ByteBuf data = dummyData(); final int padding = 10; final AtomicInteger unprocessed = new AtomicInteger(data.readableBytes() + padding); doAnswer(new Answer<Integer>() { @Over...
public String toJSON() { final HashMap<String, Object> artifactStoreAsHashMap = new HashMap<>(); artifactStoreAsHashMap.put("id", getId()); artifactStoreAsHashMap.put("storeId", getStoreId()); artifactStoreAsHashMap.put("configuration", this.getConfiguration().getConfigurationAsMap(true)...
@Test public void shouldSerializeToJson() { final PluggableArtifactConfig config = new PluggableArtifactConfig("id1", "Store-ID", create("Foo", false, "Bar")); final String actual = config.toJSON(); assertThat(actual, is("{\"configuration\":{\"Foo\":\"Bar\"},\"id\":\"id1\",\"storeId\":\"St...
@Override public Predicate createPredicate(Expression source, String expression, Object[] properties) { return doCreateJsonPathExpression(source, expression, properties, true); }
@Test public void testPredicate() { // Test books.json file Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/books.json")); Language lan = context.resolveLanguage("jsonpath"); Predicate pre = lan.createPredicate("$.store...
@Override public void activateClusterStateVersion(int clusterStateVersion, NodeInfo node, Waiter<ActivateClusterStateVersionRequest> externalWaiter) { var waiter = new RPCActivateClusterStateVersionWaiter(externalWaiter); Target connection = getConnection(node); if ( ! connection.isValid())...
@Test void activateClusterStateVersion_sends_version_activation_rpc() { var f = new Fixture<ActivateClusterStateVersionRequest>(); var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses(); f.communicator.activateClusterStateVersion(12345, cf.cluster().getNod...
public PutMessageResult putHalfMessage(MessageExtBrokerInner messageInner) { return store.putMessage(parseHalfMessageInner(messageInner)); }
@Test public void testPutHalfMessage() { when(messageStore.putMessage(any(MessageExtBrokerInner.class))) .thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); PutMessageResult result = transactionBridge.putHalfMessage(createM...
@CheckForNull public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) { if (sourceLine == null) { return null; } DecorationDataHolder decorationDataHolder = new DecorationDataHolder(); if (StringUtils.isNotBlank(highlighting)) ...
@Test public void should_handle_highlighting_too_long() { String sourceLine = "abc"; String highlighting = "0,5,c"; String symbols = ""; assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo("<span class=\"c\">abc</span>"); }
public static UTypeVar create(String name, UType lowerBound, UType upperBound) { return new UTypeVar(name, lowerBound, upperBound); }
@Test public void serialization() { UType nullType = UPrimitiveType.create(TypeKind.NULL); UType charSequenceType = UClassType.create("java.lang.CharSequence", ImmutableList.<UType>of()); SerializableTester.reserializeAndAssert(UTypeVar.create("T", nullType, charSequenceType)); }
@Override public void loadConfiguration(NacosLoggingProperties loggingProperties) { Log4j2NacosLoggingPropertiesHolder.setProperties(loggingProperties); String location = loggingProperties.getLocation(); loadConfiguration(location); }
@Test void testLoadConfiguration() { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration contextConfiguration = loggerContext.getConfiguration(); assertEquals(0, contextConfiguration.getLoggers().size()); log4J2NacosLoggingAdapter.loadConfigurati...
public static void insert( final UnsafeBuffer termBuffer, final int termOffset, final UnsafeBuffer packet, final int length) { if (0 == termBuffer.getInt(termOffset)) { termBuffer.putBytes(termOffset + HEADER_LENGTH, packet, HEADER_LENGTH, length - HEADER_LENGTH); te...
@Test void shouldInsertIntoEmptyBuffer() { final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocate(256)); final int termOffset = 0; final int srcOffset = 0; final int length = 256; packet.putInt(srcOffset, length, LITTLE_ENDIAN); TermRebuilder.insert(ter...
public Jwt convertJwtRecordToJwt(JwtRecord jwtRecord) { return new Jwt( jwtRecord.tokenValue(), jwtRecord.issuedAt(), jwtRecord.expiresAt(), jwtRecord.headers(), jwtRecord.claims() ); }
@Test void givenJwtRecord_whenConvertJwtRecordToJwt_thenCorrectlyConverted() { // Given JwtRecord jwtRecord = new JwtRecord( "tokenValue", Map.of("alg", "RS256", "typ", "JWT"), Map.of("sub", "user123", "iss", "issuer", "aud", "audience"), ...
@Override public String toString() { StringBuilder sb = new StringBuilder("{"); addField(sb, "\"userUuid\": ", this.userUuid, true); addField(sb, "\"userLogin\": ", this.userLogin, true); addField(sb, "\"name\": ", this.name, true); addField(sb, "\"email\": ", this.email, true); addField(sb, "...
@Test void toString_givenUserUuidAndUserLogin_returnValidJSON() { UserNewValue userNewValue = new UserNewValue("userUuid", "userLogin"); String jsonString = userNewValue.toString(); assertValidJSON(jsonString); }
@VisibleForTesting MaestroWorkflow getMaestroWorkflow(String workflowId) { return withRetryableQuery( GET_MAESTRO_WORKFLOW, stmt -> stmt.setString(1, workflowId), result -> { if (result.next()) { return maestroWorkflowFromResult(result); } return n...
@Test public void testGetMaestroWorkflow() throws Exception { WorkflowDefinition wfd = loadWorkflow(TEST_WORKFLOW_ID1); assertEquals(TEST_WORKFLOW_ID1, wfd.getWorkflow().getId()); WorkflowDefinition definition = workflowDao.addWorkflowDefinition(wfd, wfd.getPropertiesSnapshot().extractProperties()...
public static int findMessage(String expectedMessage) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logMessage = logList.get(i).getLogMessage(); if (logMessage.contains(expectedMessage)) { cou...
@Test void testFindMessage2() { Log log = mock(Log.class); DubboAppender.logList.add(log); when(log.getLogMessage()).thenReturn("message"); when(log.getLogLevel()).thenReturn(Level.ERROR); log = mock(Log.class); DubboAppender.logList.add(log); when(log.getLogM...
public void moveBullet(float offset) { var currentPosition = bullet.getPosition(); bullet.setPosition(currentPosition + offset); }
@Test void testMoveBullet() { controller.moveBullet(1.5f); assertEquals(1.5f, controller.bullet.getPosition(), 0); }
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = trees.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = b; for (int i...
@Test public void testBank32nhQuantile() { test(Loss.quantile(0.5), "bank32nh", Bank32nh.formula, Bank32nh.data, 0.0909); }
public Long combiInsert( RowMetaInterface rowMeta, Object[] row, Long val_key, Long val_crc ) throws KettleDatabaseException { String debug = "Combination insert"; DatabaseMeta databaseMeta = meta.getDatabaseMeta(); try { if ( data.prepStatementInsert == null ) { // first time: construct prepared ...
@Test public void testCombiInsert() throws Exception { combinationLookup.combiInsert( any( RowMetaInterface.class ), any( Object[].class ), anyLong(), anyLong() ); verify( databaseMeta, times( 2 ) ).supportsAutoGeneratedKeys(); }
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type =...
@Test public void applyGeneratesNumberUsingJavaTypeFloatPrimitive() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "number"); objectNode.put("existingJavaType"...
public static Map<String, Object> convertValues(final Map<String, Object> data, final ConfigurationRequest configurationRequest) throws ValidationException { final Map<String, Object> configuration = Maps.newHashMapWithExpectedSize(data.size()); final Map<String, Map<String, Object>> configurationFields...
@Test public void testConvertValues() throws Exception { final ImmutableMap<String, String> dropdownChoices = ImmutableMap.of( "a", "1", "b", "2"); final ConfigurationRequest cr = new ConfigurationRequest(); cr.addField(new TextField("string", "string", "defau...
public static Criterion matchOduSignalId(OduSignalId oduSignalId) { return new OduSignalIdCriterion(oduSignalId); }
@Test public void testMatchOduSignalIdMethod() { OduSignalId odu = oduSignalId(1, 80, new byte[]{2, 1, 1, 3, 1, 1, 3, 1, 1, 3}); Criterion matchoduSignalId = Criteria.matchOduSignalId(odu); OduSignalIdCriterion oduSignalIdCriterion = checkAndConvert(matchoduSignalId, ...
@Override public boolean find(Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { try { final boolean found; if(containerService.isContainer(file)) { ...
@Test public void testFindNotFound() throws Exception { assertFalse(new AzureFindFeature(session, null).find(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)))); }
@Override public TapiNodeRef getNodeRef(TapiNodeRef nodeRef) throws NoSuchElementException { updateCache(); TapiNodeRef ret = null; try { ret = tapiNodeRefList.stream() .filter(nodeRef::equals) .findFirst().get(); } catch (NoSuchEle...
@Test(expected = NoSuchElementException.class) public void testGetNodeRefWhenEmpty() { tapiResolver.getNodeRef(deviceId); }
public static boolean isQuorumCandidate(final ClusterMember[] clusterMembers, final ClusterMember candidate) { int possibleVotes = 0; for (final ClusterMember member : clusterMembers) { if (NULL_POSITION == member.logPosition || compareLog(candidate, member) < 0) { ...
@Test void isQuorumCandidateReturnFalseWhenQuorumIsNotReached() { final ClusterMember candidate = newMember(2, 10, 800); final ClusterMember[] members = new ClusterMember[] { newMember(10, 2, 100), newMember(20, 18, 6), newMember(30, 10, 800), ...
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider) throws OutsideScopeException { return resolveScopeFromLifecycle(provider, true); }
@Test public void lifecycleCheckEnd_shouldFailIfEndedWithHandler() { TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED); AutoDisposePlugins.setOutsideScopeHandler( e -> { // Swallow the exception. }); testSource(resolveScopeFromLifecycle(li...
@VisibleForTesting protected static String getInsertStatement( ObjectIdentifier materializedTableIdentifier, String definitionQuery, Map<String, String> dynamicOptions) { return String.format( "INSERT INTO %s\n%s", generateTableWithDynamic...
@Test void testGenerateInsertStatementWithDynamicOptions() { ObjectIdentifier materializedTableIdentifier = ObjectIdentifier.of("catalog", "database", "table"); String definitionQuery = "SELECT * FROM source_table"; Map<String, String> dynamicOptions = new HashMap<>(); ...
public void asyncSend(String destination, Message<?> message, SendCallback sendCallback, long timeout, int delayLevel) { if (Objects.isNull(message) || Objects.isNull(message.getPayload())) { log.error("asyncSend failed. destination:{}, message is null ", destination); throw new ...
@Test public void testAsyncBatchSendMessage() { List<Message> messages = new ArrayList<>(); for (int i = 0; i < 3; i++) { messages.add(MessageBuilder.withPayload("payload" + i).build()); } try { rocketMQTemplate.asyncSend(topic, messages, new SendCallback() { ...
@Override public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { return builder.build(stream); }
@Test public void testUnmarshal() throws Exception { InputStream stream = IOConverter.toInputStream(new File("src/test/resources/data.ics")); MockEndpoint endpoint = getMockEndpoint("mock:result"); endpoint.expectedBodiesReceived(createTestCalendar()); template.sendBody("direct:unm...
void start() throws TransientKinesisException { ImmutableMap.Builder<String, ShardRecordsIterator> shardsMap = ImmutableMap.builder(); for (ShardCheckpoint checkpoint : initialCheckpoint) { shardsMap.put(checkpoint.getShardId(), createShardIterator(kinesis, checkpoint)); } shardIteratorsMap.set(sh...
@Test public void shouldStartReadingSuccessiveShardsAfterReceivingShardClosedException() throws Exception { when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class); when(firstIterator.findSuccessiveShardRecordIterators()) .thenReturn(ImmutableList.of(thirdIterator, fourt...
@Override public ArchivedExecutionGraph getArchivedExecutionGraph( JobStatus jobStatus, @Nullable Throwable cause) { return ArchivedExecutionGraph.createSparseArchivedExecutionGraphWithJobVertices( jobInformation.getJobID(), jobInformation.getName(), ...
@Test void testArchivedJobVerticesPresent() throws Exception { final JobGraph jobGraph = createJobGraph(); jobGraph.setSnapshotSettings( new JobCheckpointingSettings( CheckpointCoordinatorConfiguration.builder().build(), null)); final ArchivedExecutio...
public final Map<DecodeHintType, Object> getReaderHintMap() { return readerHintMap; }
@Test final void testGetReaderHintMap() throws IOException { try (BarcodeDataFormat instance = new BarcodeDataFormat()) { Map<DecodeHintType, Object> result = instance.getReaderHintMap(); assertNotNull(result); } }
public boolean createDataConnection(DataConnectionCatalogEntry dl, boolean replace, boolean ifNotExists) { if (replace) { dataConnectionStorage.put(dl.name(), dl); listeners.forEach(TableListener::onTableChanged); return true; } else { boolean added = data...
@Test public void when_createsDuplicateDataConnectionIfReplace_then_succeeds() { // given DataConnectionCatalogEntry dataConnectionCatalogEntry = dataConnection(); // when dataConnectionResolver.createDataConnection(dataConnectionCatalogEntry, true, false); // then ...
@Override public int ncol() { return df.ncol(); }
@Test public void testNcols() { System.out.println("ncol"); assertEquals(5, df.ncol()); }
@Override public DataSourceProvenance getProvenance() { return new AggregateDataSourceProvenance(this); }
@Test public void testACDSIterationOrder() { MockOutputFactory factory = new MockOutputFactory(); String[] featureNames = new String[] {"X1","X2"}; double[] featureValues = new double[] {1.0, 2.0}; List<Example<MockOutput>> first = new ArrayList<>(); first.add(new ArrayExamp...
@Override public boolean isValid() { // Validate type/devices type(); devices(); return super.isValid() && hasOnlyFields(ALLOWED, NAME, LATITUDE, LONGITUDE, UI_TYPE, RACK_ADDRESS, OWNER, TYPE, DEVICES, LOC_IN_PEERS); }
@Test public void sampleValidConfig() { ObjectNode node = new TmpJson() .props(NAME, TYPE) .arrays(DEVICES) .node(); cfg = new BasicRegionConfig(); cfg.init(regionId(R1), BASIC, node, mapper, delegate); assertTrue("not valid: " + cfg, ...
@Override @MethodNotAvailable public void removeAll() { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveAll() { adapter.removeAll(); }
public synchronized boolean hasStartOfBlock() { return startOfBlockIndex >= 0; }
@Test public void testHasStartOfBlock() { assertFalse(instance.hasStartOfBlock(), "Unexpected initial value"); instance.write(MllpProtocolConstants.START_OF_BLOCK); assertTrue(instance.hasStartOfBlock()); instance.reset(); assertFalse(instance.hasStartOfBlock()); i...
protected boolean isFactMappingValueToSkip(FactMappingValue factMappingValue) { return factMappingValue.getRawValue() == null; }
@Test public void isFactMappingValueToSkip() { FactIdentifier factIdentifier = FactIdentifier.create("MyInstance", String.class.getCanonicalName()); ExpressionIdentifier expressionIdentifier = ExpressionIdentifier.create("MyProperty", FactMappingType.GIVEN); FactMappingValue factMappingValu...
public Ticket add(long delay, TimerHandler handler, Object... args) { if (handler == null) { return null; } Utils.checkArgument(delay > 0, "Delay of a ticket has to be strictly greater than 0"); final Ticket ticket = new Ticket(this, now(), delay, handler, args); ...
@Test public void testAddFaultyHandler() { ZTicket.Ticket ticket = tickets.add(10, null); assertThat(ticket, nullValue()); }
public static String[] getTableNames(String statement) { return splitTableNames(statement); }
@Test void getTableNames() { String sql = "print VersionT"; assertArrayEquals(new String[] {"VersionT"}, PrintStatementExplainer.getTableNames(sql)); sql = "print VersionT, Buyers, r, rr, vvv"; assertArrayEquals( new String[] {"VersionT", "Buyers", "r", "rr", "vvv"}...
@Override public boolean start() throws IOException { LOG.info("Starting reader using {}", initCheckpoint); try { shardReadersPool = createShardReadersPool(); shardReadersPool.start(); } catch (TransientKinesisException e) { throw new IOException(e); } return advance(); }
@Test public void startReturnsFalseIfNoDataAtTheBeginning() throws IOException { assertThat(reader.start()).isFalse(); }
@Override public <R> R eval(Mode mode, String luaScript, ReturnType returnType) { return eval(mode, luaScript, returnType, Collections.emptyList()); }
@Test public void testEvalResultMapping() { testInCluster(redissonClient -> { RScript script = redissonClient.getScript(StringCodec.INSTANCE); Long res = script.eval(RScript.Mode.READ_ONLY, "return 1;", RScript.ReturnType.INTEGER, integers -> integers.stream().map...
@InvokeOnHeader(Web3jConstants.SHH_NEW_IDENTITY) void shhNewIdentity(Message message) throws IOException { Request<?, ShhNewIdentity> request = web3j.shhNewIdentity(); setRequestId(message, request); ShhNewIdentity response = request.send(); boolean hasError = checkForError(message, ...
@Test public void shhNewIdentityTest() throws Exception { ShhNewIdentity response = Mockito.mock(ShhNewIdentity.class); Mockito.when(mockWeb3j.shhNewIdentity()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getAddress()).thenReturn("tes...
public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); // FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenar...
@Test void testIsMatch() { URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=test"); URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test"); assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl)); }
Object getCellValue(Cell cell, Schema.FieldType type) { ByteString cellValue = cell.getValue(); int valueSize = cellValue.size(); switch (type.getTypeName()) { case BOOLEAN: checkArgument(valueSize == 1, message("Boolean", 1)); return cellValue.toByteArray()[0] != 0; case BYTE: ...
@Test public void shouldFailTooLongByteValue() { byte[] value = new byte[3]; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> PARSER.getCellValue(cell(value), BYTE)); checkMessage(exception.getMessage(), "Byte has to be 1-byte long bytearray"); }
@Override public void process(MetricsPacket.Builder builder) { Set<DimensionId> dimensionsToRetain = builder.getDimensionIds(); dimensionsToRetain.removeAll(blocklistDimensions); builder.retainDimensions(dimensionsToRetain); }
@Test public void public_dimensions_are_retained() { var builder = new MetricsPacket.Builder(toServiceId("foo")) .putDimension(toDimensionId(APPLICATION_ID), "app"); var processor = new PublicDimensionsProcessor(); processor.process(builder); assertEquals(1, builder....
public static Object eval(String expression, Map<String, Object> context) { return eval(expression, context, ListUtil.empty()); }
@Test public void qlExpressTest(){ final ExpressionEngine engine = new QLExpressEngine(); final Dict dict = Dict.of() .set("a", 100.3) .set("b", 45) .set("c", -199.100); final Object eval = engine.eval("a-(b-c)", dict, null); assertEquals(-143.8, (double)eval, 0); }
public static long getEpochValueInSeconds(String epoch) { final String seconds; if (epoch.length() >= 13) { //this is in milliseconds - reduce to seconds seconds = epoch.substring(0, 10); } else { seconds = epoch; } long results = 0; tr...
@Test public void testGetEpochValueInSeconds() throws ParseException { String milliseconds = "1550538553466"; long expected = 1550538553; long result = DateUtil.getEpochValueInSeconds(milliseconds); assertEquals(expected, result); milliseconds = "blahblahblah"; expec...
@Override public void stopTrackingAndReleaseAllClusterPartitions() { clusterPartitions.values().stream() .map(DataSetEntry::getPartitionIds) .forEach(shuffleEnvironment::releasePartitionsLocally); clusterPartitions.clear(); }
@Test void stopTrackingAndReleaseAllClusterPartitions() throws Exception { final TestingShuffleEnvironment testingShuffleEnvironment = new TestingShuffleEnvironment(); final CompletableFuture<Collection<ResultPartitionID>> shuffleReleaseFuture = new CompletableFuture<>(); tes...
public void setResourceBase(String resourceBase) { handler.setResourceBase(resourceBase); }
@Test void setsResourceBase() throws Exception { environment.setResourceBase("/woo"); assertThat(handler.getResourceBase()).isEqualTo(handler.newResource("/woo").toString()); }
@Override public void createNamespace(Namespace namespace, Map<String, String> meta) { Preconditions.checkArgument( !namespace.isEmpty(), "Cannot create namespace with invalid name: %s", namespace); Preconditions.checkArgument( isValidateNamespace(namespace), "Cannot support multi part...
@Test public void testNamespaceExists() { Namespace namespace = Namespace.of("dbname_exists"); catalog.createNamespace(namespace, meta); assertThat(catalog.namespaceExists(namespace)).as("Should true to namespace exist").isTrue(); assertThat(catalog.namespaceExists(Namespace.of("db2", "db2", "ns2"))...
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDe...
@Test public void testObserveOnly() { int[][] qData = new int[][]{ // / A B C { 100, 40, 40, 20 }, // abs { 100, 100, 100, 100 }, // maxCap { 100, 90, 10, 0 }, // used { 80, 10, 20, 50 }, // pending { 0, 0, 0, 0 }, // reserved { 2, 1, 1, 0 }, // a...
public synchronized GpuDeviceInformation parseXml(String xmlContent) throws YarnException { InputSource inputSource = new InputSource(new StringReader(xmlContent)); SAXSource source = new SAXSource(xmlReader, inputSource); try { return (GpuDeviceInformation) unmarshaller.unmarshal(source); }...
@Test public void testParseMissingInnerTags() throws IOException, YarnException { File f =new File("src/test/resources/nvidia-smi-output-missing-tags2.xml"); String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8); GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); GpuDevi...
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params, Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir, ApplicationPackage applicationPackage, SessionZooKeeperCli...
@Test public void require_that_file_reference_of_application_package_is_written_to_zk() throws Exception { prepare(testApp); assertTrue(curator.exists(sessionPath(1).append(APPLICATION_PACKAGE_REFERENCE_PATH))); }
@Udf public Long trunc(@UdfParameter final Long val) { return val; }
@Test public void shouldTruncateSimpleBigDecimalPositive() { assertThat(udf.trunc(new BigDecimal("0.0")), is(new BigDecimal("0"))); assertThat(udf.trunc(new BigDecimal("1.23")), is(new BigDecimal("1"))); assertThat(udf.trunc(new BigDecimal("1.0")), is(new BigDecimal("1"))); assertThat(udf.trunc(new Bi...
public TreeSelection[] getTreeObjects( final Tree tree, Tree selectionTree, Tree coreObjectsTree ) { List<TreeSelection> objects = new ArrayList<TreeSelection>(); if ( selectionTree != null && !selectionTree.isDisposed() && tree.equals( selectionTree ) ) { TreeItem[] selection = selectionTree.getSelectio...
@Test public void getTreeObjects_getStepById() { SpoonTreeDelegate std = spy( new SpoonTreeDelegate( spoon ) ); Tree selection = mock( Tree.class ); Tree core = mock( Tree.class ); TreeItem item = mock( TreeItem.class ); PluginInterface step = mock( PluginInterface.class ); PluginRegistry reg...
protected void patchLoadBalancerClass(Service current, Service desired) { if (current.getSpec().getLoadBalancerClass() != null && desired.getSpec().getLoadBalancerClass() == null) { desired.getSpec().setLoadBalancerClass(current.getSpec().getLoadBalancerClass()); } }
@Test public void testLoadBalancerClassPatching() { KubernetesClient client = mock(KubernetesClient.class); Service current = new ServiceBuilder() .withNewMetadata() .withNamespace(NAMESPACE) .withName(RESOURCE_NAME) .endMetad...
public static CommonsConfigurationRetryConfiguration of(final Configuration configuration) throws ConfigParseException { CommonsConfigurationRetryConfiguration obj = new CommonsConfigurationRetryConfiguration(); try{ obj.getConfigs().putAll(obj.getProperties(configuration.subset(RETRY_CONFIG...
@Test public void testFromPropertiesFile() throws ConfigurationException { Configuration config = CommonsConfigurationUtil.getConfiguration(PropertiesConfiguration.class, TestConstants.RESILIENCE_CONFIG_PROPERTIES_FILE_NAME); CommonsConfigurationRetryConfiguration retryConfiguration = CommonsConfig...
@Override public Set<Network> networks() { return osNetworkStore.networks(); }
@Test public void testGetNetworks() { createBasicNetworks(); assertEquals("Number of network did not match", 1, target.networks().size()); }
public static List<String> validateXml(InputStream schemaStream, String xmlString) throws Exception { return validateXml(schemaStream, xmlString, null); }
@Test public void testValidXmlAgainstValidSchema() throws Exception { InputStream schemaStream = new FileInputStream("target/test-classes/io/github/microcks/util/valid-schema.xsd"); String validXml = """ <note> <to>Tove</to> <from>Jani</from> <h...
@Override protected void analyzeDependency(final Dependency dependency, final Engine engine) throws AnalysisException { // batch request component-reports for all dependencies synchronized (FETCH_MUTIX) { if (reports == null) { try { requestDelay(); ...
@Test public void should_analyzeDependency_only_warn_when_transport_error_from_sonatype() throws Exception { // Given OssIndexAnalyzer analyzer = new OssIndexAnalyzerThrowing502(); getSettings().setBoolean(Settings.KEYS.ANALYZER_OSSINDEX_WARN_ONLY_ON_REMOTE_ERRORS, true); an...
@Override public ConfigOperateResult insertOrUpdateCas(String srcIp, String srcUser, ConfigInfo configInfo, Map<String, Object> configAdvanceInfo) { try { ConfigInfoStateWrapper configInfoState = findConfigInfoState(configInfo.getDataId(), configInfo.getGroup(), c...
@Test void testInsertOrUpdateCasOfUpdateConfigSuccess() { Map<String, Object> configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); configAdvanceInfo.put("desc", "desc11"); configAdvanceInfo.put("use", "use2233"); configAdvanceInfo.put("effec...
public static void updateDetailMessage( @Nullable Throwable root, @Nullable Function<Throwable, String> throwableToMessage) { if (throwableToMessage == null) { return; } Throwable it = root; while (it != null) { String newMessage = throwableToMessage....
@Test void testUpdateDetailMessageOfNullWithoutException() { ExceptionUtils.updateDetailMessage(null, t -> "new message"); }
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldValidateTerminateQuery() { // Given: givenTerminate(); // When: commandFactory.create(configuredStatement, executionContext); // Then: verify(executionContext).getPersistentQuery(QUERY_ID); verify(query1).close(); }
public static <T> RestResult<T> failed() { return RestResult.<T>builder().withCode(500).build(); }
@Test void testFailedWithCode() { RestResult<String> restResult = RestResultUtils.failed(400, "content"); assertRestResult(restResult, 400, null, "content", false); }
@Override public boolean expireEntry(K key, Duration ttl) { return get(expireEntryAsync(key, ttl)); }
@Test public void testExpireEntry() { RMapCacheNative<String, String> testMap = redisson.getMapCacheNative("map"); testMap.put("key", "value"); testMap.expireEntry("key", Duration.ofMillis(20000)); assertThat(testMap.remainTimeToLive("key")).isBetween(19800L, 20000L); }
public int orCardinality(BitmapCollection bitmaps) { ImmutableRoaringBitmap left = reduceInternal(); ImmutableRoaringBitmap right = bitmaps.reduceInternal(); if (!_inverted) { if (!bitmaps._inverted) { return ImmutableRoaringBitmap.orCardinality(left, right); } return _numDocs - ri...
@Test(dataProvider = "orCardinalityTestCases") public void testOrCardinality(int numDocs, ImmutableRoaringBitmap left, boolean leftInverted, ImmutableRoaringBitmap right, boolean rightInverted, int expected) { assertEquals(new BitmapCollection(numDocs, leftInverted, left).orCardinality( new BitmapCo...
public boolean eval(ContentFile<?> file) { // TODO: detect the case where a column is missing from the file using file's max field id. return new MetricsEvalVisitor().eval(file); }
@Test public void testIntegerNotIn() { boolean shouldRead = new StrictMetricsEvaluator(SCHEMA, notIn("id", INT_MIN_VALUE - 25, INT_MIN_VALUE - 24)) .eval(FILE); assertThat(shouldRead).as("Should match: all values !=5 and !=6").isTrue(); shouldRead = new StrictMetricsEvaluator(...
@Override public Optional<ProfileDescription> compare(final ProfileDescription next) { // Filter out profiles with matching checksum final Optional<ProfileDescription> found = repository.stream() .filter(description -> Objects.equals(description.getChecksum(), next.getChecksum())) ...
@Test public void testEqual() throws Exception { // Managed profile final ProfileDescription remote = new ProfileDescription( ProtocolFactory.get(), new Checksum(HashAlgorithm.md5, "d41d8cd98f00b204e9800998ecf8427e"), null) { @Override public boolean isLatest(...
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowStatement) { return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s...
@Test void assertCreateWithSelectTablespace() { SQLStatement sqlStatement = parseSQL(PSQL_SELECT_TABLESPACES); SelectStatementContext selectStatementContext = mock(SelectStatementContext.class); when(selectStatementContext.getSqlStatement()).thenReturn((SelectStatement) sqlStatement); ...
public boolean isShallowClone() { return shallowClone; }
@Test void byDefaultShallowCloneShouldBeOff() { assertFalse(git("http://url", "foo").isShallowClone()); assertFalse(git("http://url", "foo", false).isShallowClone()); assertFalse(git("http://url", "foo", null).isShallowClone()); assertTrue(git("http://url", "foo", true).isShallowClon...
static int addHash(int originalHash, int addedHash) { return originalHash + HUGE_PRIME * addedHash; }
@Test public void testAddHashIsAssociative() { int hash = MerkleTreeUtil.addHash(0, 1); hash = MerkleTreeUtil.addHash(hash, 2); hash = MerkleTreeUtil.addHash(hash, 3); int hash2 = MerkleTreeUtil.addHash(0, 3); hash2 = MerkleTreeUtil.addHash(hash2, 1); hash2 = MerkleT...
@Override public void execute(GraphModel graphModel) { Graph graph = graphModel.getGraphVisible(); execute(graph); }
@Test public void testColumnReplace() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1); graphModel.getNodeTable().addColumn(WeightedDegree.WDEGREE, String.class); WeightedDegree d = new WeightedDegree(); d.execute(graphModel); }
public static <T> List<T> parseArray(String text, Class<T> clazz) { if (StringUtil.isBlank(text)) { return Collections.emptyList(); } return JSON_FACADE.parseArray(text, clazz); }
@Test public void assertParseArray() { Assert.assertEquals(Collections.emptyList(), JSONUtil.parseArray(null, Foo.class)); Assert.assertEquals(Collections.emptyList(), JSONUtil.parseArray(" ", Foo.class)); Assert.assertEquals( EXPECTED_FOO_ARRAY, JSONUtil.par...
@Override public Output run(RunContext runContext) throws Exception { URI from = new URI(runContext.render(this.from)); final PebbleExpressionPredicate predicate = getExpressionPredication(runContext); final Path path = runContext.workingDir().createTempFile(".ion"); long processe...
@Test void shouldFilterGivenInvalidRecordsForInclude() throws Exception { // Given RunContext runContext = runContextFactory.of(); FilterItems task = FilterItems .builder() .from(generateKeyValueFile(TEST_INVALID_ITEMS, runContext).toString()) .filterCond...
@CanIgnoreReturnValue @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } if (value == null && !allowNullValues) { throw new NullPointerException("value == null"); } Node<K, V> created = find(key, true); V result = created....
@Test @SuppressWarnings("ModifiedButNotUsed") public void testPutNonComparableKeyFails() { LinkedTreeMap<Object, String> map = new LinkedTreeMap<>(); assertThrows(ClassCastException.class, () -> map.put(new Object(), "android")); }