focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public BytesInput getBytes() { // The Page Header should include: blockSizeInValues, numberOfMiniBlocks, totalValueCount if (deltaValuesToFlush != 0) { flushBlockBuffer(); } return BytesInput.concat( config.toBytesInput(), BytesInput.fromUnsignedVarInt(totalValueCount),...
@Test public void shouldReturnCorrectOffsetAfterInitialization() throws IOException { long[] data = new long[2 * blockSize + 3]; for (int i = 0; i < data.length; i++) { data[i] = i * 32; } writeData(data); reader = new DeltaBinaryPackingValuesReader(); BytesInput bytes = writer.getBytes...
@Primary @Bean("OkHttpClient") public OkHttpClient provide(Configuration config, SonarQubeVersion version) { OkHttpClientBuilder builder = new OkHttpClientBuilder(); builder.setConnectTimeoutMs(DEFAULT_CONNECT_TIMEOUT_IN_MS); builder.setReadTimeoutMs(DEFAULT_READ_TIMEOUT_IN_MS); // no need to define...
@Test public void get_returns_a_OkHttpClient_with_default_configuration() throws Exception { OkHttpClient client = underTest.provide(settings.asConfig(), sonarQubeVersion); assertThat(client.connectTimeoutMillis()).isEqualTo(10_000); assertThat(client.readTimeoutMillis()).isEqualTo(10_000); assertTha...
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testAnd() { Evaluator evaluator = new Evaluator(STRUCT, and(equal("x", 7), notNull("z"))); assertThat(evaluator.eval(TestHelpers.Row.of(7, 0, 3))).as("7, 3 => true").isTrue(); assertThat(evaluator.eval(TestHelpers.Row.of(8, 0, 3))).as("8, 3 => false").isFalse(); assertThat(evaluator....
public static ParseResult parse(String text) { Map<String, String> localProperties = new HashMap<>(); String intpText = ""; String scriptText = null; Matcher matcher = REPL_PATTERN.matcher(text); if (matcher.find()) { String headingSpace = matcher.group(1); intpText = matcher.group(2); ...
@Test void testParagraphTextLocalPropertiesNoText() { ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse("%spark.pyspark(pool=pool_1)"); assertEquals("spark.pyspark", parseResult.getIntpText()); assertEquals(1, parseResult.getLocalProperties().size()); assertEquals("pool_1", parse...
public static SeataMQProducer createSingle(String nameServer, String producerGroup) throws MQClientException { return createSingle(nameServer, null, producerGroup, null); }
@Test public void testCreateSingle() throws Exception { SeataMQProducerFactory.createSingle("127.0.0.1:9876", "test"); Assertions.assertThrows(NotSupportYetException.class, () -> SeataMQProducerFactory.createSingle("127.0.0.1:9876", "test")); SeataMQProducer producer = SeataMQProducerFactor...
public static Builder builder() { return new Builder(); }
@TestTemplate public void rowDeltaWithDeletesAndDuplicates() { assumeThat(formatVersion).isGreaterThan(1); assertThat(listManifestFiles()).isEmpty(); table .newRowDelta() .addRows(FILE_A) .addRows(DataFiles.builder(SPEC).copy(FILE_A).build()) .addRows(FILE_A) .addD...
@Override public Map<Errors, Integer> errorCounts() { Errors error = error(); if (error != Errors.NONE) { // Minor optimization since the top-level error applies to all partitions if (version < 5) return Collections.singletonMap(error, data.partitionErrors()....
@Test public void testErrorCountsNoTopLevelError() { for (short version : LEADER_AND_ISR.allVersions()) { LeaderAndIsrResponse response; if (version < 5) { List<LeaderAndIsrPartitionError> partitions = createPartitions("foo", asList(Errors.NONE...
@Override public CloseableIterator<String> readLines(Component file) { requireNonNull(file, "Component should not be null"); checkArgument(file.getType() == FILE, "Component '%s' is not a file", file); Optional<CloseableIterator<String>> linesIteratorOptional = reportReader.readFileSource(file.getReportA...
@Test public void fail_with_ISE_when_file_has_no_source() { assertThatThrownBy(() -> { underTest.readLines(builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("File 'ReportCo...
static BigtableDataSettings translateReadToVeneerSettings( @NonNull BigtableConfig config, @NonNull BigtableReadOptions options, @Nullable BigtableReadOptions optionsFromBigtableOptions, @NonNull PipelineOptions pipelineOptions) throws IOException { BigtableDataSettings.Builder setting...
@Test public void testVeneerReadSettings() throws Exception { BigtableConfig config = BigtableConfig.builder() .setProjectId(ValueProvider.StaticValueProvider.of("project")) .setInstanceId(ValueProvider.StaticValueProvider.of("instance")) .setAppProfileId(ValueProvider....
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "from" ) String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } if (!BEGIN_YEAR.matcher(val).find()) { // please notice the regex strictly req...
@Test void invokeParamStringNull() { FunctionTestUtil.assertResultError(dateFunction.invoke((String) null), InvalidParametersEvent.class); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(containerService.isContainer(file)) { final PathAttributes attributes = new PathAttributes(); ...
@Test public void testReadWhitespaceInKey() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path directory = new S3Direc...
@JsonCreator public static WindowInfo of( @JsonProperty(value = "type", required = true) final WindowType type, @JsonProperty(value = "size") final Optional<Duration> size, @JsonProperty(value = "emitStrategy") final Optional<OutputRefinement> emitStrategy) { return new WindowInfo(type, size, em...
@Test(expected = IllegalArgumentException.class) public void shouldThrowIfSizeProvidedButNotRequired() { WindowInfo.of(SESSION, Optional.of(Duration.ofSeconds(10)), Optional.empty()); }
protected int calculateConcurency() { final int customLimit = filterConcurrencyCustom.get(); return customLimit != DEFAULT_FILTER_CONCURRENCY_LIMIT ? customLimit : filterConcurrencyDefault.get(); }
@Test void validateFilterGlobalConcurrencyLimitOverride() { config.setProperty("zuul.filter.concurrency.limit.default", 7000); config.setProperty("zuul.ConcInboundFilter.in.concurrency.limit", 4000); final int[] limit = {0}; class ConcInboundFilter extends BaseFilter { ...
@VisibleForTesting static String getContainerImageForJob(DataflowPipelineOptions options) { String containerImage = options.getSdkContainerImage(); if (containerImage == null) { // If not set, construct and return default image URL. return getDefaultContainerImageUrl(options); } else if (cont...
@Test public void testGetContainerImageForJobFromOptionWithPlaceholder() { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); options.setSdkContainerImage("gcr.io/IMAGE/foo"); for (Environments.JavaVersion javaVersion : Environments.JavaVersion.values()) { S...
public Optional<String> fetchFileIfNotModified(String url) throws IOException { return fetchFile(url, true); }
@Test public void doNotRetrieveIfNotModified() throws Exception { this.server.enqueue(new MockResponse() .setResponseCode(200) .setBody("foobar") .setHeader("Last-Modified", "Fri, 18 Aug 2017 15:02:41 GMT")); this.server.enqueue(new MockResponse() ...
@Udf(description = "Converts a TIMESTAMP value into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'" + " The system default time zone is used when no time zone is explicitly ...
@Test public void shoudlReturnNull() { // When: final Object result = udf.formatTimestamp(null, "yyyy-MM-dd'T'HH:mm:ss.SSS"); // Then: assertNull(result); }
@Override public Optional<IndexSet> get(final String indexSetId) { return this.indexSetsCache.get() .stream() .filter(indexSet -> Objects.equals(indexSet.id(), indexSetId)) .map(indexSetConfig -> (IndexSet) mongoIndexSetFactory.create(indexSetConfig)) ...
@Test public void indexSetsCacheShouldReturnCachedList() { final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class); final List<IndexSetConfig> indexSetConfigs = Collections.singletonList(indexSetConfig); when(indexSetService.findAll()).thenReturn(indexSetConfigs); final Lis...
public boolean isAllBindingTables(final Collection<String> logicTableNames) { if (logicTableNames.isEmpty()) { return false; } Optional<BindingTableRule> bindingTableRule = findBindingTableRule(logicTableNames); if (!bindingTableRule.isPresent()) { return false; ...
@Test void assertIsAllBindingTableWhenLogicTablesIsEmpty() { assertFalse(createMaximumShardingRule().isAllBindingTables(Collections.emptyList())); }
public CompletableFuture<Boolean> put( @Nonnull final ReceiptSerial receiptSerial, final long receiptExpiration, final long receiptLevel, @Nonnull final UUID accountUuid) { // fail early if given bad inputs Objects.requireNonNull(receiptSerial); Objects.requireNonNull(accountUuid); ...
@Test void testPut() throws ExecutionException, InterruptedException { final long receiptExpiration = 42; final long receiptLevel = 3; CompletableFuture<Boolean> put; // initial insert should return true put = redeemedReceiptsManager.put(receiptSerial, receiptExpiration, receiptLevel, AuthHelper....
@Override public void createFunction(SqlInvokedFunction function, boolean replace) { checkCatalog(function); checkFunctionLanguageSupported(function); checkArgument(!function.hasVersion(), "function '%s' is already versioned", function); QualifiedObjectName functionName = functi...
@Test public void testGetFunctionMetadata() { createFunction(FUNCTION_POWER_TOWER_DOUBLE, true); FunctionHandle handle1 = getLatestFunctionHandle(FUNCTION_POWER_TOWER_DOUBLE.getFunctionId()); assertGetFunctionMetadata(handle1, FUNCTION_POWER_TOWER_DOUBLE); createFunction(FUNCTIO...
@VisibleForTesting Collection<String> getVolumesLowOnSpace() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Going to check the following volumes disk space: " + volumes); } Collection<String> lowVolumes = new ArrayList<String>(); for (CheckedVolume volume : volumes.values()) { ...
@Test public void testChecking2NameDirsOnOneVolume() throws IOException { Configuration conf = new Configuration(); File nameDir1 = new File(BASE_DIR, "name-dir1"); File nameDir2 = new File(BASE_DIR, "name-dir2"); nameDir1.mkdirs(); nameDir2.mkdirs(); conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_...
public void computeCpd(Component component, Collection<Block> originBlocks, Collection<Block> duplicationBlocks) { CloneIndex duplicationIndex = new PackedMemoryCloneIndex(); populateIndex(duplicationIndex, originBlocks); populateIndex(duplicationIndex, duplicationBlocks); List<CloneGroup> duplications...
@Test public void add_no_duplication_when_no_duplicated_blocks() { settings.setProperty("sonar.cpd.xoo.minimumTokens", 10); Collection<Block> originBlocks = singletonList( new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIn...
public static Result<Boolean> isRowsEquals(TableMeta tableMetaData, List<Row> oldRows, List<Row> newRows) { if (!CollectionUtils.isSizeEquals(oldRows, newRows)) { return Result.build(false, null); } return compareRows(tableMetaData, oldRows, newRows); }
@Test public void isRowsEquals() { TableMeta tableMeta = Mockito.mock(TableMeta.class); Mockito.when(tableMeta.getPrimaryKeyOnlyName()).thenReturn(Arrays.asList(new String[]{"pk"})); Mockito.when(tableMeta.getTableName()).thenReturn("table_name"); List<Row> rows = new ArrayList<>();...
public static TbMathArgumentValue fromMessageBody(TbMathArgument arg, String argKey, Optional<ObjectNode> jsonNodeOpt) { Double defaultValue = arg.getDefaultValue(); if (jsonNodeOpt.isEmpty()) { return defaultOrThrow(defaultValue, "Message body is empty!"); } var json = jsonN...
@Test public void test_fromMessageBody_then_valueEmpty() { TbMathArgument tbMathArgument = new TbMathArgument(TbMathArgumentType.MESSAGE_BODY, "TestKey"); ObjectNode msgData = JacksonUtil.newObjectNode(); msgData.putNull("TestKey"); //null value Throwable thrown = assertThro...
public long cardinality() { HLLRepresentation representation = store(); return representation == null ? 0 : representation.cardinality(); }
@Test(dataProvider = "representations") public void testSingleThreadOperationsRepresentation(HLLRepresentation representation, long expected) { assertThat(representation.cardinality()).isEqualTo(0L); for (int i = 0; i < 1000; i++) { representation.set(("zt-" + i).getBytes(StandardCharsets.US_ASC...
public ParquetMetadataCommand(Logger console) { super(console); }
@Test public void testParquetMetadataCommand() throws IOException { File file = parquetFile(); ParquetMetadataCommand command = new ParquetMetadataCommand(createLogger()); command.targets = Arrays.asList(file.getAbsolutePath()); command.setConf(new Configuration()); Assert.assertEquals(0, command....
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final JsonNode event; try { event = objectMapper.readTree(payload); if (event == null || event.isMissingNode()) { throw new ...
@Test public void decodeMessagesHandlesPacketbeatV8Messages() throws Exception { final Message message = codec.decode(messageFromJson("packetbeat-mongodb-v8.json")); assertThat(message).isNotNull(); assertThat(message.getSource()).isEqualTo("example.local"); assertThat(message.getTim...
static SamplingFlags toSamplingFlags(int flags) { switch (flags) { case 0: return EMPTY; case FLAG_SAMPLED_SET: return NOT_SAMPLED; case FLAG_SAMPLED_SET | FLAG_SAMPLED: return SAMPLED; case FLAG_SAMPLED_SET | FLAG_SAMPLED | FLAG_DEBUG: return DEBUG; cas...
@Test void toSamplingFlags_returnsConstantsAndHasNiceToString() { assertThat(toSamplingFlags(SamplingFlags.EMPTY.flags)) .isSameAs(SamplingFlags.EMPTY) .hasToString(""); assertThat(toSamplingFlags(SamplingFlags.NOT_SAMPLED.flags)) .isSameAs(SamplingFlags.NOT_SAMPLED) .hasToString("NOT_SA...
@Override public void insertEdge(E edge) { checkNotNull(edge, "Edge cannot be null"); checkArgument(edges.isEmpty() || src().equals(edge.dst()), "Edge destination must be the same as the current path source"); edges.add(0, edge); }
@Test public void insertEdge() { MutablePath<TestVertex, TestEdge> p = new DefaultMutablePath<>(); p.insertEdge(new TestEdge(B, C)); p.insertEdge(new TestEdge(A, B)); validatePath(p, A, C, 2); }
@Override public void close() throws IOException { if (mClosed.getAndSet(true)) { return; } mLocalOutputStream.close(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(mFile))) { ObjectMetadata meta = new ObjectMetadata(); meta.setContentLength(mFile.length(...
@Test @PrepareForTest(COSOutputStream.class) public void testConstructor() throws Exception { PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(mFile); String errorMessage = "protocol doesn't support output"; PowerMockito.whenNew(FileOutputStream.class).withArguments(mFile) ...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test public void testNotNotAnd() { final Predicate parsed = PredicateExpressionParser.parse("!!com.linkedin.data.it.AlwaysTruePredicate & com.linkedin.data.it.AlwaysFalsePredicate"); Assert.assertEquals(parsed.getClass(), AndPredicate.class); final List<Predicate> andChildren = ((AndPredicate) parsed)...
public static Applications copyApplications(Applications source) { Applications result = new Applications(); copyApplications(source, result); return updateMeta(result); }
@Test public void testCopyApplicationsIfNotNullReturnApplications() { Application application1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Application application2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED); ...
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_map_of_non_serializable_value() { Map<String, NonSerializableObject> original = new HashMap<>(); original.put("key", new NonSerializableObject("value")); Object cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSame(o...
@Override public Flux<ReactiveRedisConnection.BooleanResponse<RenameCommand>> renameNX(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null...
@Test public void testRenameNX() { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyFo...
@Override public void execute(ComputationStep.Context context) { PostMeasuresComputationCheck.Context extensionContext = new ContextImpl(); for (PostMeasuresComputationCheck extension : extensions) { extension.onCheck(extensionContext); } }
@Test public void do_nothing_if_no_extensions() { // no failure newStep().execute(new TestComputationStepContext()); }
@Override public @Nullable V replace(K key, V value) { requireNonNull(key); requireNonNull(value); int[] oldWeight = new int[1]; @SuppressWarnings("unchecked") K[] nodeKey = (K[]) new Object[1]; @SuppressWarnings("unchecked") V[] oldValue = (V[]) new Object[1]; long[] now = new long[1...
@CheckMaxLogLevel(ERROR) @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_replaceConditionally( BoundedLocalCache<MutableInt, Int> cache, CacheContext context) { testForBrokenEquality(cache, context, key -> { boolean r...
@Override public int hashCode() { return Objects.hash( threadName, threadState, activeTasks, standbyTasks, mainConsumerClientId, restoreConsumerClientId, producerClientIds, adminClientId); }
@Test public void shouldBeEqualIfSameObject() { final ThreadMetadata same = new ThreadMetadataImpl( THREAD_NAME, THREAD_STATE, MAIN_CONSUMER_CLIENT_ID, RESTORE_CONSUMER_CLIENT_ID, PRODUCER_CLIENT_IDS, ADMIN_CLIENT_ID, ACTIVE...
public static URI createRemainingURI(URI originalURI, Map<String, Object> params) throws URISyntaxException { String s = createQueryString(params); if (s.isEmpty()) { s = null; } return createURIWithQuery(originalURI, s); }
@Test public void testCreateRemainingURIEncoding() throws Exception { // the uri is already encoded, but we create a new one with new query parameters String uri = "http://localhost:23271/myapp/mytest?columns=name%2Ctotalsens%2Cupsens&username=apiuser"; // these are the parameters which is ...
@GuardedBy("evictionLock") protected void setMaximum(long maximum) { throw new UnsupportedOperationException(); }
@Test(dataProvider = "caches") @CacheSpec(compute = Compute.SYNC, population = Population.EMPTY, maximumSize = Maximum.FULL) public void drain_blocksCapacity(BoundedLocalCache<Int, Int> cache, CacheContext context, Eviction<Int, Int> eviction) { checkDrainBlocks(cache, () -> eviction.setMaximum(0)); }
static public long copy(Reader input, Writer output) throws IOException { char[] buffer = new char[1 << 12]; long count = 0; for (int n = 0; (n = input.read(buffer)) >= 0; ) { output.write(buffer, 0, n); count += n; } return count; }
@Test public void testCopy() throws Exception { char[] arr = "testToString".toCharArray(); Reader reader = new CharArrayReader(arr); Writer writer = new CharArrayWriter(); long count = IOTinyUtils.copy(reader, writer); assertEquals(arr.length, count); }
public static Ip4Address valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new Ip4Address(bytes); }
@Test(expected = NullPointerException.class) public void testInvalidValueOfNullString() { Ip4Address ipAddress; String fromString = null; ipAddress = Ip4Address.valueOf(fromString); }
public H3IndexResolution getResolution() { return _resolution; }
@Test public void withSomeData() throws JsonProcessingException { String confStr = "{\n" + " \"resolution\": [13, 5, 6]\n" + "}"; H3IndexConfig config = JsonUtils.stringToObject(confStr, H3IndexConfig.class); assertFalse(config.isDisabled(), "Unexpected disabled"); H3Inde...
public List<String> listTableNames(String catalogName, String dbName) { Optional<ConnectorMetadata> connectorMetadata = getOptionalMetadata(catalogName); ImmutableSet.Builder<String> tableNames = ImmutableSet.builder(); if (connectorMetadata.isPresent()) { try { conne...
@Test public void testListTblNames(@Mocked HiveMetaStoreClient metaStoreThriftClient) throws TException, DdlException { new Expectations() { { metaStoreThriftClient.getAllTables("db2"); result = Lists.newArrayList("tbl2"); minTimes = 0; ...
static String generateDatabaseName(String baseString) { return generateResourceId( baseString, ILLEGAL_DATABASE_NAME_CHARS, REPLACE_DATABASE_NAME_CHAR, MAX_DATABASE_NAME_LENGTH, TIME_FORMAT); }
@Test public void testGenerateDatabaseNameShouldReplacePeriod() { String testBaseString = "Test.DB.Name"; String actual = generateDatabaseName(testBaseString); assertThat(actual).matches("test-db-name-\\d{8}-\\d{6}-\\d{6}"); }
@Override public void updateService(Service service) { checkNotNull(service, ERR_NULL_SERVICE); checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()), ERR_NULL_SERVICE_UID); k8sServiceStore.updateService(service); log.info(String.format(MSG_SERVICE, s...
@Test(expected = IllegalArgumentException.class) public void testUpdateUnregisteredService() { target.updateService(SERVICE); }
public static Function<Integer, Integer> composeFunctions(Function<Integer, Integer> f1, Function<Integer, Integer> f2) { return f1.andThen(f2); }
@Test public void testComposeFunctions() { Function<Integer, Integer> timesTwo = x -> x * 2; Function<Integer, Integer> square = x -> x * x; Function<Integer, Integer> composed = FunctionComposer.composeFunctions(timesTwo, square); assertEquals("Expected output of composed functions is 36", 36, (int...
public void setError(final int errorCode) { if (this.destroyed) { LOG.warn("ThreadId: {} already destroyed, ignore error code: {}", this.data, errorCode); return; } this.lock.lock(); try { if (this.destroyed) { LOG.warn("ThreadId: {} al...
@Test public void testSetError() throws Exception { this.id.setError(100); assertEquals(100, this.errorCode); CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { ThreadIdTest.this.id.setError(99); ...
public static void main(String[] args) { var conUnix = new ConfigureForUnixVisitor(); var conDos = new ConfigureForDosVisitor(); var zoom = new Zoom(); var hayes = new Hayes(); hayes.accept(conDos); // Hayes modem with Dos configurator zoom.accept(conDos); // Zoom modem with Dos configurator ...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public IcebergSourceSplit deserialize(int version, byte[] serialized) throws IOException { switch (version) { case 1: return IcebergSourceSplit.deserializeV1(serialized); case 2: return IcebergSourceSplit.deserializeV2(serialized, caseSensitive); case 3: return ...
@Test public void testDeserializeV1() throws Exception { final List<IcebergSourceSplit> splits = SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 1, 1); for (IcebergSourceSplit split : splits) { byte[] result = split.serializeV1(); IcebergSourceSplit deserialized = serial...
static TypeName getEventNativeType(TypeName typeName) { if (typeName instanceof ParameterizedTypeName) { return TypeName.get(byte[].class); } String simpleName = ((ClassName) typeName).simpleName(); if (simpleName.equals(Utf8String.class.getSimpleName())) { retur...
@Test public void testGetEventNativeTypeParameterized() { assertEquals( getEventNativeType( ParameterizedTypeName.get( ClassName.get(DynamicArray.class), TypeName.get(Address.class))), (TypeName.get(byte[].class))); ...
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory( final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration, final Configuration jobConfiguration, final Configuration clusterConfiguration, final boolean is...
@Test void testInvalidStrategySpecifiedInJobConfig() { final Configuration conf = new Configuration(); conf.set(RestartStrategyOptions.RESTART_STRATEGY, "invalid-strategy"); assertThatThrownBy( () -> RestartBackoffTimeStrategyFactoryLo...
public static RawTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); TransactionType transactionType = getTransactionType(transaction); switch (transactionType) { case EIP1559: return decodeEIP155...
@Test public void testDecoding1559() { final RawTransaction rawTransaction = createEip1559RawTransaction(); final Transaction1559 transaction1559 = (Transaction1559) rawTransaction.getTransaction(); final byte[] encodedMessage = TransactionEncoder.encode(rawTransaction); final Strin...
@Override public boolean isClosed() { State currentState = state.get(); return currentState == State.Closed || currentState == State.Closing; }
@Test public void testIsClosed() throws Exception { ClientConfigurationData conf = new ClientConfigurationData(); conf.setServiceUrl("pulsar://localhost:6650"); initializeEventLoopGroup(conf); PulsarClientImpl client = new PulsarClientImpl(conf, eventLoopGroup); assertFalse(c...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertOtherString() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("clob").dataType("clob").build(); Column column = XuguTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), ...
List<ProviderInfo> mergeProviderInfo(List<String> userDatas, List<String> configDatas) { // 是否自己缓存运算后的结果?? TODO List<ProviderInfo> providers = SofaRegistryHelper.parseProviderInfos(userDatas); // 交叉比较 if (CommonUtils.isNotEmpty(providers) && CommonUtils.isNotEmpty(configDatas)) { ...
@Test public void mergeProviderInfo() throws Exception { SofaRegistrySubscribeCallback callback = new SofaRegistrySubscribeCallback(); // null + null List<ProviderInfo> result = callback.mergeProviderInfo(null, null); Assert.assertTrue(CommonUtils.isEmpty(result)); // 空 + nul...
@Override public void register(ProviderConfig config) { String appName = config.getAppName(); if (!registryConfig.isRegister()) { if (LOGGER.isInfoEnabled(appName)) { LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE)); } re...
@Test public void testOnlyPublish() throws InterruptedException { Field registedAppField = null; try { registedAppField = MeshRegistry.class.getDeclaredField("registedApp"); registedAppField.setAccessible(true); } catch (NoSuchFieldException e) { e.printS...
@Override public Expression getExpression(String tableName, Alias tableAlias) { // 只有有登陆用户的情况下,才进行数据权限的处理 LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser == null) { return null; } // 只有管理员类型的用户,才进行数据权限的处理 if (ObjectUtil.notEqual(...
@Test // 全部数据权限 public void testGetExpression_allDeptDataPermission() { try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock = mockStatic(SecurityFrameworkUtils.class)) { // 准备参数 String tableName = "t_user"; Alias tableAlias = new Alia...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("sds.listing.chunksize")); }
@Test public void testListRoot() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path directory = new Path("/", EnumSet.of(AbstractPath.Type.directory, Path.Type.volume)); final AttributedList<Path> list = new SDSListService(session, nodeid).list( ...
public static SerializableFunction<byte[], Row> getProtoBytesToRowFromSchemaFunction( String schemaString, String messageName) { Descriptors.Descriptor descriptor = getDescriptorFromProtoSchema(schemaString, messageName); ProtoDynamicMessageSchema<DynamicMessage> protoDynamicMessageSchema = Prot...
@Test public void testProtoBytesToRowSchemaStringGenerateSerializableFunction() { SerializableFunction<byte[], Row> protoBytesToRowFunction = ProtoByteUtils.getProtoBytesToRowFromSchemaFunction(PROTO_STRING_SCHEMA, "MyMessage"); Assert.assertNotNull(protoBytesToRowFunction); }
public static int parseMajorVersion(String version) { if (version.endsWith("-ea")) { version = version.substring(0, version.length() - 3); } if (version.startsWith("1.")) { version = version.substring(2, 3); } else { int dot = version.indexOf("."); if (dot != -1) { versio...
@Test public void parseVersion() throws Exception { assertEquals(8, CommonUtils.parseMajorVersion("1.8.0")); assertEquals(11, CommonUtils.parseMajorVersion("11.0.1")); assertEquals(9, CommonUtils.parseMajorVersion("9.0.1")); }
@Override public void negativeAcknowledge(MessageId messageId) { consumerNacksCounter.increment(); negativeAcksTracker.add(messageId); // Ensure the message is not redelivered for ack-timeout, since we did receive an "ack" unAckedMessageTracker.remove(MessageIdAdvUtils.discardBatch(...
@Test public void testClose() { Exception checkException = null; try { if (consumer != null) { consumer.negativeAcknowledge(new MessageIdImpl(-1, -1, -1)); consumer.close(); } } catch (Exception e) { checkException = e; ...
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf, QueuePath childQueuePath) { setTemplateEntriesForChild(conf, childQueuePath, false); }
@Test public void testTwoLevelWildcardTemplate() { conf.set(getTemplateKey(TEST_QUEUE_ROOT_WILDCARD, "capacity"), "6w"); conf.set(getTemplateKey(TEST_QUEUE_TWO_LEVEL_WILDCARDS, "capacity"), "5w"); new AutoCreatedQueueTemplate(conf, TEST_QUEUE_A) .setTemplateEntriesForChild(conf, TEST_QUEUE_AB...
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { final SMBSession.DiskShareWrapper share = session.openShare(file); try { if(file.isDirectory()) { try (final Directory entry = share.get().openDirectory(new SMBPa...
@Test public void testTimestampFileNotfound() throws Exception { final TransferStatus status = new TransferStatus(); final Path home = new DefaultHomeFinderService(session).find(); final Path f = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); ...
@NonNull static Predicate<NotificationTemplate> matchReasonType(String reasonType) { return template -> template.getSpec().getReasonSelector().getReasonType() .equals(reasonType); }
@Test void matchReasonTypeTest() { var template = createNotificationTemplate("fake-template"); assertThat(ReasonNotificationTemplateSelectorImpl.matchReasonType("new-comment-on-post") .test(template)).isTrue(); assertThat(ReasonNotificationTemplateSelectorImpl.matchReasonType("f...
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query));...
@Test public void fail_to_create_query_on_tag_using_eq_operator_and_values() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(EQ).setValues(asList("java")).build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) ...
@Bean @ConditionalOnMissingBean(LdapOperations.class) public LdapTemplate ldapTemplate(final LdapContextSource ldapContextSource) { return new LdapTemplate(ldapContextSource); }
@Test public void testLdapTemplate() { LdapContextSource ldapContextSource = new LdapContextSource(); LdapTemplate ldapTemplate = ldapConfiguration.ldapTemplate(ldapContextSource); assertNotNull(ldapTemplate); }
@Override public void publishLong(MetricDescriptor descriptor, long value) { publishNumber(descriptor, value, LONG); }
@Test public void when_moreMetrics() throws Exception { jmxPublisher.publishLong(newDescriptor() .withMetric("c") .withTag("tag1", "a") .withTag("tag2", "b"), 1L); jmxPublisher.publishLong(newDescriptor() .withMetric("d") ...
@Override public List<Instance> getAllInstances(String serviceName) throws NacosException { return getAllInstances(serviceName, new ArrayList<>()); }
@Test void testGetAllInstanceFromFailoverEmpty() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo("group1@@service1"); when(serviceInfoHolder.getFailoverServiceInfo(anyString(), anyString(), anyString())).thenRetur...
public JDiscCookieWrapper[] getWrappedCookies() { List<Cookie> cookies = getCookies(); if (cookies == null) { return null; } List<JDiscCookieWrapper> cookieWrapper = new ArrayList<>(cookies.size()); for(Cookie cookie : cookies) { cookieWrapper.add(JDiscCo...
@Test void testGetWrapedCookies() { URI uri = URI.create("http://example.yahoo.com/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value"); DiscFilterRequest request = new DiscFi...
public static Matcher<HttpRequest> pathStartsWith(String pathPrefix) { if (pathPrefix == null) throw new NullPointerException("pathPrefix == null"); if (pathPrefix.isEmpty()) throw new NullPointerException("pathPrefix is empty"); return new PathStartsWith(pathPrefix); }
@Test void pathStartsWith_matched_prefix() { when(httpRequest.path()).thenReturn("/foo/bar"); assertThat(pathStartsWith("/foo").matches(httpRequest)).isTrue(); }
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvWithMultipleCarriageReturn() { CharSequence value = "\r\r"; CharSequence expected = "\"\r\r\""; escapeCsv(value, expected); }
public HadoopCatalog() {}
@Test public void testCreateTableDefaultSortOrder() throws Exception { TableIdentifier tableIdent = TableIdentifier.of("db", "ns1", "ns2", "tbl"); Table table = hadoopCatalog().createTable(tableIdent, SCHEMA, SPEC); SortOrder sortOrder = table.sortOrder(); assertThat(sortOrder.orderId()).as("Order ID...
@Override public void maybeExport(Supplier<TraceDescription> traceDescriptionSupplier) { if (samplingStrategy.shouldSample()) { wrappedExporter.maybeExport(traceDescriptionSupplier); } }
@Test void sampling_decision_is_deferred_to_provided_sampler() { var exporter = mock(TraceExporter.class); var sampler = mock(SamplingStrategy.class); when(sampler.shouldSample()).thenReturn(true, false); var samplingExporter = new SamplingTraceExporter(exporter, sampler); s...
@Override public double quantile(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } return Gamma.inverseRegularizedIncompleteGamma(k, p) * theta; }
@Test public void testQuantile() { System.out.println("quantile"); GammaDistribution instance = new GammaDistribution(3, 2.1); instance.rand(); assertEquals(0.4001201, instance.quantile(0.001), 1E-7); assertEquals(0.9156948, instance.quantile(0.01), 1E-7); assertEqual...
public void set(PropertyKey key, Object value) { set(key, value, Source.RUNTIME); }
@Test public void getMalformedIntThrowsException() { mThrown.expect(IllegalArgumentException.class); mConfiguration.set(PropertyKey.WEB_THREADS, 2147483648L); // bigger than MAX_INT }
public void pushWithoutAck(String connectionId, ServerRequest request) { Connection connection = connectionManager.getConnection(connectionId); if (connection != null) { try { connection.request(request, 3000L); } catch (ConnectionAlreadyClosedException e) { ...
@Test void testPushWithoutAck() { Mockito.when(connectionManager.getConnection(Mockito.any())).thenReturn(grpcConnection); try { Mockito.when(grpcConnection.request(Mockito.any(), Mockito.eq(3000L))).thenThrow(ConnectionAlreadyClosedException.class); rpcPushService.pushWithou...
@VisibleForTesting static String getFlinkMetricIdentifierString(MetricKey metricKey) { MetricName metricName = metricKey.metricName(); ArrayList<String> scopeComponents = getNameSpaceArray(metricKey); List<String> results = scopeComponents.subList(0, scopeComponents.size() / 2); resu...
@Test void testGetFlinkMetricIdentifierString() { MetricKey key = MetricKey.create("step", MetricName.named(DEFAULT_NAMESPACE, "name")); assertThat(FlinkMetricContainer.getFlinkMetricIdentifierString(key)) .isEqualTo("key.value.name"); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == GET_UNKNOWN_SUB_COMMAND_NAME) { returnCommand = getUnknownMember(reader); }...
@Test public void testJavaLangClass() { String inputCommand1 = ReflectionCommand.GET_JAVA_LANG_CLASS_SUB_COMMAND_NAME + "\n" + "java.lang.String\ne\n"; String inputCommand2 = ReflectionCommand.GET_JAVA_LANG_CLASS_SUB_COMMAND_NAME + "\n" + "java.lang" + ".FOOOOO\ne\n"; // does not exist try { command.execu...
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = originalGlyphIds; for (String feature : FEATURES_IN_ORDER) { if (!gsubData.isFeatureSupported(feature)) { LOG.debug("the fe...
@Test void testApplyTransforms_e_kar() { // given List<Integer> glyphsAfterGsub = Arrays.asList(438, 89, 94, 101); // when List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("বেলা")); // then assertEquals(glyphsAfterGsub, result); }
@Override public String encrypt(String clearText) { try { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, loadSecretFile()); byte[] cipherData = cipher.doFinal(clearText.getBytes(StandardCharsets.UTF_8.name())); retur...
@Test public void encrypt_bad_key() throws Exception { URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/bad_secret_key.txt"); AesECBCipher cipher = new AesECBCipher(new File(resource.toURI()).getCanonicalPath()); assertThatThrownBy(() -> cipher.encrypt("this is a secret...
@Override public Organizations listOrganizations(String appUrl, AccessToken accessToken, int page, int pageSize) { checkPageArgs(page, pageSize); try { Organizations organizations = new Organizations(); GetResponse response = githubApplicationHttpClient.get(appUrl, accessToken, String.format("/us...
@Test public void listOrganizations_fail_if_pageSize_out_of_bounds() { UserAccessToken token = new UserAccessToken("token"); assertThatThrownBy(() -> underTest.listOrganizations(appUrl, token, 1, 0)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("'pageSize' must be a value larger than ...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldIncludeAvailableSignaturesIfNotMatchFound() { // Given: final ArrayType generic = of(GenericType.of("A")); givenFunctions( function(OTHER, true, -1, STRING, INT), function(OTHER, 0, STRING_VARARGS), function(OTHER, -1, generic) ); // When: final...
public void expand(String key, long value, RangeHandler rangeHandler, EdgeHandler edgeHandler) { if (value < lowerBound || value > upperBound) { // Value outside bounds -> expand to nothing. return; } int maxLevels = value > 0 ? maxPositiveLevels : maxNegativeLevels; ...
@Test void requireThatUpperAndLowerBoundGreaterThan0Works() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 100, 9999); Iterator<String> expectedLabels = List.of( "key=140-149", "key=100-199", "key=0-999", "ke...
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by( PredicateT predicate) { return new Filter<>(predicate); }
@Test public void testFilterParDoOutputTypeDescriptorRawWithLambda() throws Exception { @SuppressWarnings({"unchecked", "rawtypes"}) PCollection<String> output = p.apply(Create.of("hello")).apply(Filter.by(s -> true)); thrown.expect(CannotProvideCoderException.class); p.getCoderRegistry().getCoder(o...
public SearchSourceBuilder create(SearchesConfig config) { return create(SearchCommand.from(config)); }
@Test void scrollSearchDoesNotHighlight() { final SearchSourceBuilder search = this.searchRequestFactory.create(ChunkCommand.builder() .indices(Collections.singleton("graylog_0")) .range(RANGE) .build()); assertThat(search.toString()).doesNotContain("...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStart, final Range<Instant> windowEnd, final Optional<Position> position ) { try { final ReadOnlySessionStore<GenericKey, GenericRow> store = sta...
@Test public void shouldReturnEmptyIfKeyNotPresent() { // When: final Iterator<WindowedRow> rowIterator = table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS).rowIterator; // Then: assertThat(rowIterator.hasNext(), is(false)); }
public static void checkArgument(boolean expression, Object errorMessage) { if (Objects.isNull(errorMessage)) { throw new IllegalArgumentException("errorMessage cannot be null."); } if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); ...
@Test void testCheckArgument2Args1true() { Preconditions.checkArgument(true, ERRORMSG); }
public CompletableFuture<Response> executeRequest(Request request) { return executeRequest(request, () -> new AsyncCompletionHandlerBase()); }
@Test void testRedirectWithBody() throws ExecutionException, InterruptedException { server.stubFor(post(urlEqualTo("/path1")) .willReturn(aResponse() .withStatus(307) .withHeader("Location", "/path2"))); server.stubFor(post(urlEqualTo(...
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for eac...
@Test(expected=AclException.class) public void testReplaceAclEntriesMissingUser() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); Li...
@Override public ExecuteContext before(ExecuteContext context) { Object[] arguments = context.getArguments(); if (arguments[0] instanceof HystrixConcurrencyStrategy) { if (!HystrixRequestContext.isCurrentThreadInitialized()) { HystrixRequestContext.initializeContext(); ...
@Test public void testBefore() { Map<String, List<String>> header = new HashMap<>(); header.put("bar", Collections.singletonList("bar1")); header.put("foo", Collections.singletonList("foo1")); ThreadLocalUtils.addRequestTag(header); interceptor.before(context); Hystri...
public boolean satisfies(ClusterSpec other) { if ( ! other.id.equals(this.id)) return false; // ID mismatch if (other.type.isContent() || this.type.isContent()) // Allow seamless transition between content and combined return other.type.isContent() == this.type.isContent(); return ot...
@Test void testSatisfies() { var tests = Map.of( List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id2")), false, List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.container, "id1")), false, ...
@CanIgnoreReturnValue public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) { List<@Nullable Object> expected = (varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs); return containsExactlyElementsIn( expected, varargs != null && varargs.length == 1...
@Test public void iterableContainsExactlyWithDuplicatesUnexpectedItemFailure() { expectFailureWhenTestingThat(asList(1, 2, 2, 2, 2, 3)).containsExactly(1, 2, 2, 3); assertFailureValue("unexpected (2)", "2 [2 copies]"); }
private Mono<ServerResponse> listPostsByCategoryName(ServerRequest request) { final var name = request.pathVariable("name"); final var query = new PostPublicQuery(request.exchange()); var listOptions = query.toListOptions(); var newFieldSelector = listOptions.getFieldSelector() ...
@Test void listPostsByCategoryName() { ListResult<ListedPostVo> listResult = new ListResult<>(List.of()); when(postPublicQueryService.list(any(), any(PageRequest.class))) .thenReturn(Mono.just(listResult)); webTestClient.get() .uri("/categories/test/posts?page=1&size...
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { for (Class<?> t = type.getRawType(); (t != Object.class) && (t.getSuperclass() != null); t = t.getSuperclass()) { for (Method m : t.getDeclaredMethods()) { if (m.isAnnotationPresent(PostConstruct.class)) { ...
@Test public void test() throws Exception { Gson gson = new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create(); Sandwich unused = gson.fromJson("{\"bread\": \"white\", \"cheese\": \"cheddar\"}", Sandwich.class); var e = assertThrows( I...
private List<String> getNames( IMetaStore metaStore, ConnectionProvider<? extends ConnectionDetails> provider ) { try { return getMetaStoreFactory( metaStore, provider.getClassType() ).getElementNames(); } catch ( MetaStoreException mse ) { logger.error( "Error calling metastore getElementNames()", ...
@Test public void testGetNames() { addOne(); List<String> names = connectionManager.getNames(); assertEquals( 1, names.size() ); assertEquals( CONNECTION_NAME, names.get( 0 ) ); }
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void cluster_down_if_less_than_min_count_of_storage_nodes_available() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(3) .bringEntireClusterUp() .reportStorageNodeState(0, State.DOWN) .reportStorageNodeState(2, State.DOWN); final C...
@VisibleForTesting static void verifyImageMetadata(ImageMetadataTemplate metadata, Path metadataCacheDirectory) throws CacheCorruptedException { List<ManifestAndConfigTemplate> manifestsAndConfigs = metadata.getManifestsAndConfigs(); if (manifestsAndConfigs.isEmpty()) { throw new CacheCorruptedExc...
@Test public void testVerifyImageMetadata_schema1ManifestsCorrupted_containerConfigExists() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V21ManifestTemplate(), new ContainerConfigurationTemplate()); ImageMetadataTemplate metadata = new ImageMet...
public ConnectionAuthContext authorizePeer(X509Certificate cert) { return authorizePeer(List.of(cert)); }
@Test void certificate_must_match_both_san_and_cn_pattern() { RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn"); RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san"); PeerAuthorizer authorizer = createPeerAuthorizer(cr...
public Predicate getPredicate() { return predicate; }
@Test public void requireThatConstructorsWork() { assertNull(new PredicateFieldValue().getPredicate()); Predicate predicate = SimplePredicates.newPredicate(); assertEquals(predicate, new PredicateFieldValue(predicate).getPredicate()); }
@Override protected FieldValue doGet(String fieldName, EventWithContext eventWithContext) { final ImmutableMap.Builder<String, Object> dataModelBuilder = ImmutableMap.builder(); if (eventWithContext.messageContext().isPresent()) { dataModelBuilder.put("source", eventWithContext.messageC...
@Test public void templateBooleanFormatting() { final TestEvent event = new TestEvent(); final EventWithContext eventWithContext = EventWithContext.create(event, newMessage(ImmutableMap.of("success", true))); final FieldValue fieldValue = newTemplate("success: ${source.success}").doGet("tes...