focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Measure.Level getLevel() { return level; }
@Test public void getLevel_returns_object_passed_in_constructor() { assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, SOME_VALUE).getLevel()).isSameAs(SOME_LEVEL); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Map.Entry<Path, TransferStatus> file : files.entrySet()) { try { callback.delete(file.getKey()); final Stor...
@Test public void testDeleteFileWithLock() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new Path("/My files", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path fileInRoom = new Path(room, new AlphanumericRandomStringSe...
@Override public void clear() { throw new UnsupportedOperationException("RangeSet is immutable"); }
@Test(expected = UnsupportedOperationException.class) public void clear() throws Exception { RangeSet rs = new RangeSet(5); rs.clear(); }
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@Test void testFunctionDependingOnInputWithFunctionHierarchy() { IdentityMapper4<String> function = new IdentityMapper4<String>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes(function, BasicTypeInfo.STRING_TYPE_INFO); assertThat(ti).isEqualTo(BasicTypeInfo.STRIN...
public void putValue(String fieldName, @Nullable Object value) { _fieldToValueMap.put(fieldName, value); }
@Test public void testDifferentNumberOfKeysWithSomeSameValueNotEqual() { GenericRow first = new GenericRow(); first.putValue("one", 1); first.putValue("two", 2); GenericRow second = new GenericRow(); second.putValue("one", 1); Assert.assertNotEquals(first, second); }
@Override public void updateSmsSendResult(Long id, Boolean success, String apiSendCode, String apiSendMsg, String apiRequestId, String apiSerialNo) { SmsSendStatusEnum sendStatus = success ? SmsSendStatusEnum.SUCCESS : SmsSendStatusEnum...
@Test public void testUpdateSmsSendResult() { // mock 数据 SmsLogDO dbSmsLog = randomSmsLogDO( o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus())); smsLogMapper.insert(dbSmsLog); // 准备参数 Long id = dbSmsLog.getId(); Boolean success = randomBoolean...
@Nonnull @Override public Optional<Signature> parse( @Nullable String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } final String generalizedStr = str.toLowerCase().trim(); if (!generalizedStr.contains("...
@Test void RSASSA_PSS() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaSignatureMapper jcaSignatureMapper = new JcaSignatureMapper(); Optional<Signature> signatureOptional = jcaSignatureMa...
@Override @CheckForNull public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) { String bundleKey = propertyToBundles.get(key); String value = null; if (bundleKey != null) { try { ResourceBundle resourceBundle = ResourceBundle.getBundle(bundle...
@Test public void return_default_value_if_missing_key() { assertThat(underTest.message(Locale.ENGLISH, "bla_bla_bla", "default")).isEqualTo("default"); assertThat(underTest.message(Locale.FRENCH, "bla_bla_bla", "default")).isEqualTo("default"); }
public BigtableRowToBeamRowFlat(Schema schema, Map<String, Set<String>> columnsMapping) { this.schema = schema; this.columnsMapping = columnsMapping; }
@Test public void testBigtableRowToBeamRowFlat() { Map<String, Set<String>> columnsMapping = ImmutableMap.of( FAMILY_TEST, ImmutableSet.of(BOOL_COLUMN, LONG_COLUMN, STRING_COLUMN, DOUBLE_COLUMN)); PCollection<Row> rows = pipeline .apply(Create.of(bigtableRow(1), bigtab...
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder) throws CoderException { if (value == null) { return noopMutationDetector(); } else { return new CodedValueMutationDetector<>(value, coder); } }
@Test public void testMutationBasedOnStructuralValue() throws Exception { AtomicInteger value = new AtomicInteger(); MutationDetector detector = MutationDetectors.forValueWithCoder(value, new ForSDKMutationDetectionTestCoder()); // Even though we modified the value, we are relying on the fact that...
public static <T> KryoCoder<T> of() { return of(PipelineOptionsFactory.create(), Collections.emptyList()); }
@Test public void testBasicCoding() throws IOException { final KryoCoder<ClassToBeEncoded> coder = KryoCoder.of(OPTIONS, k -> k.register(ClassToBeEncoded.class)); assertEncoding(coder); }
public boolean containsDatabase(final String databaseName) { return databases.containsKey(databaseName); }
@Test void assertContainsDatabase() { ShardingSphereRule globalRule = mock(ShardingSphereRule.class); ShardingSphereDatabase database = mockDatabase(mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), new MockedDataSource(), globalRule); Map<String, ShardingSphereDatabase> databases = new Hash...
private GetRegisterLeasePResponse acquireRegisterLease( final long workerId, final int estimatedBlockCount) throws IOException { return retryRPC(() -> { LOG.info("Requesting lease with workerId {}, blockCount {}", workerId, estimatedBlockCount); return mClient.requestRegisterLease(GetRegisterLease...
@Test public void acquireRegisterLeaseFailure() { assertThrows(FailedToAcquireRegisterLeaseException.class, () -> acquireRegisterLease(false)); }
static final String addFunctionParameter(ParameterDescriptor descriptor, RuleBuilderStep step) { final String parameterName = descriptor.name(); // parameter name needed by function final Map<String, Object> parameters = step.parameters(); if (Objects.isNull(parameters)) { return nul...
@Test public void addFunctionParameterSyntaxOk_WhenVariableParameterStringContainsBadChar() { String parameterName = "foo"; String parameterValue = "bar\"123"; RuleBuilderStep step = mock(RuleBuilderStep.class); Map<String, Object> params = Map.of(parameterName, parameterValue); ...
public static void executeAsyncNotify(Runnable runnable) { ASYNC_NOTIFY_EXECUTOR.execute(runnable); }
@Test void testExecuteAsyncNotify() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); Runnable runnable = atomicInteger::incrementAndGet; ConfigExecutor.executeAsyncNotify(runnable); TimeUnit.MILLISECONDS.sleep(20); ...
public static ImmutableList<String> splitToLowercaseTerms(String identifierName) { if (ONLY_UNDERSCORES.matcher(identifierName).matches()) { // Degenerate case of names which contain only underscore return ImmutableList.of(identifierName); } return TERM_SPLITTER .splitToStream(identifier...
@Test public void splitToLowercaseTerms_separatesTerms_withUnderscoreSeparator() { String identifierName = "UNDERSCORE_SEPARATED"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("underscore", "separated"); }
public double logp(int[] o, int[] s) { if (o.length != s.length) { throw new IllegalArgumentException("The observation sequence and state sequence are not the same length."); } int n = s.length; double p = MathEx.log(pi[s[0]]) + MathEx.log(b.get(s[0], o[0])); for (in...
@Test public void testJointLogp() { System.out.println("joint logp"); HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b)); int[] o = {0, 0, 1, 1, 0, 1, 1, 0}; int[] s = {0, 0, 1, 1, 1, 1, 1, 0}; double expResult = -9.51981; double result = hmm.logp(o, s); assert...
@Override public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { throw new ReadOnlyBufferException(); }
@Test public void shouldRejectSetBytes1() { assertThrows(UnsupportedOperationException.class, new Executable() { @Override public void execute() throws IOException { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (InputStream) null, 0); } }); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { return this.toAttributes(session.toPath(file)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Failure to read attribu...
@Test public void testFindRoot() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()...
@Override public NodeId getMasterFor(DeviceId deviceId) { checkPermission(CLUSTER_READ); checkNotNull(deviceId, DEVICE_ID_NULL); return store.getMaster(deviceId); }
@Test public void getMasterFor() { mgr.setRole(NID_LOCAL, DEV_MASTER, MASTER); mgr.setRole(NID_OTHER, DEV_OTHER, MASTER); assertEquals("wrong master:", NID_LOCAL, mgr.getMasterFor(DEV_MASTER)); assertEquals("wrong master:", NID_OTHER, mgr.getMasterFor(DEV_OTHER)); //have NID...
static boolean waitUntil(Duration timeout, BooleanSupplier condition) throws InterruptedException { int waited = 0; while (!condition.getAsBoolean() && waited < timeout.toMillis()) { Thread.sleep(100L); waited += 100; } return condition.getAsBoolean(); }
@Test @DisplayName("resend unconfirmed messages") void resendUnconfirmedMessagesIntegration() throws Exception { Channel ch = connection.createChannel(); ch.confirmSelect(); Map<Long, String> outstandingConfirms = resendUnconfirmedMessages(ch); assertThat(waitUntil(Duration.ofSec...
void writeConfigToDisk() { VespaTlsConfig config = VespaZookeeperTlsContextUtils.tlsContext() .map(ctx -> new VespaTlsConfig(ctx, TransportSecurityUtils.getInsecureMixedMode())) .orElse(Vesp...
@Test public void config_is_written_correctly_with_tls_for_quorum_communication_tls_without_mixed_mode() { ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile); TlsContext tlsContext = createTlsContext(); new Configurator(builder.build()).writeConfigToDis...
public void completeDefaults(Props props) { // init string properties for (Map.Entry<Object, Object> entry : defaults().entrySet()) { props.setDefault(entry.getKey().toString(), entry.getValue().toString()); } boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), false); if ...
@Test public void completeDefaults_sets_default_values_for_sonar_search_host_and_sonar_search_port_and_random_port_for_sonar_es_port_in_non_cluster_mode() throws Exception { Properties p = new Properties(); p.setProperty("sonar.cluster.enabled", "false"); Props props = new Props(p); processProperties...
@Override public <PS extends Serializer<P>, P> KeyValueIterator<K, V> prefixScan(final P prefix, final PS prefixKeySerializer) { return new KeyValueIteratorFacade<>(inner.prefixScan(prefix, prefixKeySerializer)); }
@Test public void shouldReturnPlainKeyValuePairsForPrefixScan() { final StringSerializer stringSerializer = new StringSerializer(); when(mockedKeyValueTimestampIterator.next()) .thenReturn(KeyValue.pair("key1", ValueAndTimestamp.make("value1", 21L))) .thenReturn(KeyValue.pair...
private RemotingCommand consumeMessageDirectly(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); final ConsumeMessageDirectlyResultRequestHeader requestHeader = (ConsumeM...
@Test public void testConsumeMessageDirectly() throws Exception { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); RemotingCommand request = mock(RemotingCommand.class); when(request.getCode()).thenReturn(RequestCode.CONSUME_MESSAGE_DIRECTLY); when(request.getBody()).th...
public static CurlOption parse(String cmdLine) { List<String> args = ShellWords.parse(cmdLine); URI url = null; HttpMethod method = HttpMethod.PUT; List<Entry<String, String>> headers = new ArrayList<>(); Proxy proxy = NO_PROXY; while (!args.isEmpty()) { Str...
@Test public void must_provide_valid_method() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> CurlOption.parse("https://example.com -X NO-SUCH-METHOD")); assertThat(exception.getMessage(), is("NO-SUCH-METHOD was not a http method"));...
@Override public void removeRule(final RuleData ruleData) { Optional.ofNullable(ruleData).ifPresent(s -> CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(ruleData))); }
@Test public void testRemoveRule() { this.requestPluginHandler.handlerRule(this.ruleData); RuleData ruleData = new RuleData(); ruleData.setSelectorId("test"); ruleData.setId("test"); this.requestPluginHandler.removeRule(this.ruleData); assertNull(RequestPluginHandler....
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final Instant lower = calculateLowerBound(windowSt...
@Test @SuppressWarnings("unchecked") public void shouldSupportRangeAll() { // When: final StateQueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> partitionResult = new StateQueryResult<>(); final QueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> result = QueryResult.fo...
public byte[] getSignature() { return signature; }
@Test public void testGetSignature() { assertEquals(TestParameters.VP_ISTP_SIGNATURE, new String(chmItspHeader.getSignature(), UTF_8)); }
static UnixResolverOptions parseEtcResolverOptions() throws IOException { return parseEtcResolverOptions(new File(ETC_RESOLV_CONF_FILE)); }
@Test public void defaultValueReturnedIfNdotsOptionsNotPresent(@TempDir Path tempDir) throws IOException { File f = buildFile(tempDir, "search localdomain\n" + "nameserver 127.0.0.11\n"); assertEquals(1, parseEtcResolverOptions(f).ndots()); }
@Override public Region updateRegion(RegionId regionId, String name, Region.Type type, Annotations annots, List<Set<NodeId>> masterNodeIds) { return regionsRepo.compute(regionId, (id, region) -> { nullIsNotFound(region, NO_REGION); return new DefaultReg...
@Test(expected = ItemNotFoundException.class) public void missingUpdate() { store.updateRegion(RID1, "R1", METRO, NO_ANNOTS, MASTERS); }
boolean isModified(Namespace namespace) { Release release = releaseService.findLatestActiveRelease(namespace); List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId()); if (release == null) { return hasNormalItems(items); } Map<String, String> releasedConfiguration = GSON.fr...
@Test public void testChildNamespaceModified() { long childNamespaceId = 1, parentNamespaceId = 2; Namespace childNamespace = createNamespace(childNamespaceId); Namespace parentNamespace = createNamespace(parentNamespaceId); Release childRelease = createRelease("{\"k1\":\"v1\", \"k2\":\"v2\"}"); ...
@Override public String getGroupKeyColumnName(int groupKeyColumnIndex) { throw new AssertionError("No group key column name for result table"); }
@Test(expectedExceptions = AssertionError.class) public void testGetGroupKeyColumnName() { // Run the test _resultTableResultSetUnderTest.getGroupKeyColumnName(0); }
@Override public Boolean login(Properties properties) { if (ramContext.validate()) { return true; } loadRoleName(properties); loadAccessKey(properties); loadSecretKey(properties); loadRegionId(properties); return true; }
@Test void testLoginWithAkSk() { assertTrue(ramClientAuthService.login(akSkProperties)); assertEquals(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); assertNull(ramContext.getRamRoleName()); assert...
public static File getResourceAsFile(String resource) throws IOException { return new File(getResourceUrl(resource).getFile()); }
@Test void testGetResourceAsFileByLoader() throws IOException { File file = ResourceUtils.getResourceAsFile(ResourceUtils.class.getClassLoader(), "resource_utils_test.properties"); assertNotNull(file); }
public void start() throws Exception { start(StartMode.NORMAL); }
@Test public void testModes() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient( server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client...
@Override public ParsedLine parse(final String line, final int cursor, final ParseContext context) { final ParsedLine parsed = delegate.parse(line, cursor, context); if (context != ParseContext.ACCEPT_LINE) { return parsed; } if (UnclosedQuoteChecker.isUnclosedQuote(line)) { throw new EO...
@Test public void shouldReturnResultIfNotAcceptLine() { // Given: givenDelegateWillReturn(UNTERMINATED_LINE); // When: final ParsedLine result = parser.parse("what ever", 0, ParseContext.COMPLETE); // Then: assertThat(result, is(parsedLine)); }
@Override public void processElement(final StreamRecord<T> element) throws Exception { final T event = element.getValue(); final long previousTimestamp = element.hasTimestamp() ? element.getTimestamp() : Long.MIN_VALUE; final long newTimestamp = timestampAssigner.extractTimes...
@Test void punctuatedWatermarksBatchMode() throws Exception { OneInputStreamOperatorTestHarness<Tuple2<Boolean, Long>, Tuple2<Boolean, Long>> testHarness = createBatchHarness( WatermarkStrategy.forGenerator( ...
@Override public KTable<K, V> reduce(final Reducer<V> adder, final Reducer<V> subtractor, final Materialized<K, V, KeyValueStore<Bytes, byte[]>> materialized) { return reduce(adder, subtractor, NamedInternal.empty(), materialized); }
@Test public void shouldReduceWithInternalStoreName() { final KeyValueMapper<String, Number, KeyValue<String, Integer>> intProjection = (key, value) -> KeyValue.pair(key, value.intValue()); final KTable<String, Integer> reduced = builder .table( topic, ...
public void setBatchSize(int batchSize) { this.batchSize = checkPositive(batchSize, "batchSize"); }
@Test public void test_setBatchSize_whenZero() { ReactorBuilder builder = newBuilder(); assertThrows(IllegalArgumentException.class, () -> builder.setBatchSize(0)); }
public static ByteBuffer serializeSubscription(final Subscription subscription) { return serializeSubscription(subscription, ConsumerProtocolSubscription.HIGHEST_SUPPORTED_VERSION); }
@Test public void serializeSubscriptionShouldOrderTopics() { assertEquals( ConsumerProtocol.serializeSubscription( new Subscription(Arrays.asList("foo", "bar"), null, Arrays.asList(tp1, tp2)) ), ConsumerProtocol.serializeSubscription( new S...
public ProxyConfiguration swap(final YamlProxyConfiguration yamlConfig) { Map<String, DatabaseConfiguration> databaseConfigs = swapDatabaseConfigurations(yamlConfig.getDatabaseConfigurations()); ProxyGlobalConfiguration globalConfig = swapGlobalConfiguration(yamlConfig.getServerConfiguration()); ...
@Test void assertSwap() throws IOException { YamlProxyConfiguration yamlProxyConfig = ProxyConfigurationLoader.load("/conf/swap"); ProxyConfiguration actual = new YamlProxyConfigurationSwapper().swap(yamlProxyConfig); assertDataSources(actual); assertDatabaseRules(actual); as...
public static PartitionAwareOperationFactory extractPartitionAware(OperationFactory operationFactory) { if (operationFactory instanceof PartitionAwareOperationFactory factory) { return factory; } if (operationFactory instanceof OperationFactoryWrapper wrapper) { Operatio...
@Test public void returns_partition_aware_factory_when_supplied_factory_is_partition_aware() { PartitionAwareOpFactory factory = new PartitionAwareOpFactory(); PartitionAwareOperationFactory extractedFactory = extractPartitionAware(factory); assertInstanceOf(PartitionAwareOperationFactory.c...
public static DataMap bytesToDataMap(Map<String, String> headers, ByteString bytes) throws MimeTypeParseException, IOException { return getContentType(headers).getCodec().readMap(bytes); }
@Test(expectedExceptions = IOException.class) public void testInvalidJSONByteStringToDataMap() throws MimeTypeParseException, IOException { bytesToDataMap("application/json", ByteString.copy("helloWorld".getBytes())); }
public static <T, S> T copy(S source, T target, String... ignore) { return copy(source, target, DEFAULT_CONVERT, ignore); }
@Test public void test() throws InvocationTargetException, IllegalAccessException { Source source = new Source(); source.setAge(100); source.setName("测试"); source.setIds(new String[]{"1", "2", "3"}); source.setAge2(2); source.setBoy2(true); source.setColor(Col...
@Override public @Nullable Instant currentSynchronizedProcessingTime() { return watermarks.getSynchronizedProcessingInputTime(); }
@Test public void getSynchronizedProcessingTimeIsWatermarkSynchronizedInputTime() { when(watermarks.getSynchronizedProcessingInputTime()).thenReturn(new Instant(12345L)); assertThat(internals.currentSynchronizedProcessingTime(), equalTo(new Instant(12345L))); }
public static Map<String, String> getLogicAndActualTableMap(final RouteUnit routeUnit, final SQLStatementContext sqlStatementContext, final ShardingRule shardingRule) { if (!(sqlStatementContext instanceof TableAvailable)) { return Collections.emptyMap(); } Collection<String> tableNa...
@Test void assertGetLogicAndActualTablesFromRouteUnit() { Map<String, String> actual = TokenUtils.getLogicAndActualTableMap(getRouteUnit(), mockSQLStatementContext(), mockShardingRule()); assertThat(actual.get("foo_table"), is("foo_table_0")); assertThat(actual.get("bar_table"), is("bar_tabl...
@ReadOperation public Map<String, Object> circuitBreaker(@Selector String dstService) { List<CircuitBreakerProto.CircuitBreakerRule> rules = serviceRuleManager.getServiceCircuitBreakerRule( MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE, dstService ); Map<String, Object> polarisCircu...
@Test public void testPolarisCircuitBreaker() { contextRunner.run(context -> { PolarisCircuitBreakerEndpoint endpoint = new PolarisCircuitBreakerEndpoint(serviceRuleManager); Map<String, Object> circuitBreakerInfo = endpoint.circuitBreaker("test"); assertThat(circuitBreakerInfo).isNotNull(); assertThat(c...
public int run() throws IOException { Set<MasterInfoField> masterInfoFilter = new HashSet<>(Arrays .asList(MasterInfoField.LEADER_MASTER_ADDRESS, MasterInfoField.WEB_PORT, MasterInfoField.RPC_PORT, MasterInfoField.START_TIME_MS, MasterInfoField.UP_TIME_MS, MasterInfoField.VERSION, ...
@Test public void ZkHaSummary() throws IOException { MasterVersion primaryVersion = MasterVersion.newBuilder() .setVersion(RuntimeConstants.VERSION).setState("Primary").setAddresses( NetAddress.newBuilder().setHost("hostname1").setRpcPort(10000).build() ).build(); MasterVersion sta...
protected void doHttpRequest(final Request request, final ClientResponseCallback callback) { // Highly memory inefficient, // but buffer the request content to allow it to be replayed for // authentication retries final Request.Content content = request.getBody(); if (content ins...
@Test public void shouldTimeoutWhenRequestsAreStillOngoing() throws Exception { client.doHttpRequest(mock(Request.class), (response, headers, exception) -> { }); // the request never completes StopWatch watch = new StopWatch(); // will wait for 1 second client.stop(...
void parseArgAndAppend(String entityName, String fieldName, Object arg) { if (entityName == null || fieldName == null || arg == null) { return; } if (arg instanceof Collection) { for (Object o : (Collection<?>) arg) { String matchedValue = String.valueOf(o); api.appendDataInflue...
@Test public void testParseArgAndAppendCaseCollectionTypeArg() { final String entityName = "App"; final String fieldName = "Name"; List<Object> list = Arrays.asList(new Object(), new Object(), new Object()); { doNothing().when(api).appendDataInfluence(any(), any(), any(), any()); } aspe...
@Override public List<Intent> compile(SinglePointToMultiPointIntent intent, List<Intent> installable) { Set<Link> links = new HashSet<>(); final boolean allowMissingPaths = intentAllowsPartialFailure(intent); boolean hasPaths = false; boolean missingS...
@Test public void testSingleLongPathCompilation() { FilteredConnectPoint ingress = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)); Set<FilteredConnectPoint> egress = Sets.newHashSet(new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_2))); Single...
public static Builder builder() { return new AutoValue_HttpHeaders.Builder(); }
@Test public void builderAddHeader_withNullName_throwsNullPointerException() { assertThrows( NullPointerException.class, () -> HttpHeaders.builder().addHeader(null, "test_value")); }
public static String getGlobalRuleActiveVersionNode(final String rulePath) { return String.join("/", getGlobalRuleRootNode(), rulePath, ACTIVE_VERSION); }
@Test void assertGetGlobalRuleActiveVersionNode() { assertThat(GlobalNode.getGlobalRuleActiveVersionNode("transaction"), is("/rules/transaction/active_version")); }
@Override public void configure(Map<String, ?> configs, boolean isKey) { if (listClass != null || inner != null) { log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner); throw new ConfigException("List dese...
@Test public void testListValueDeserializerNoArgConstructorsShouldThrowKafkaExceptionDueInvalidTypeClass() { props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_TYPE_CLASS, new FakeObject()); props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_INNER_CLASS, Serdes.StringSerde.class); fi...
public static RuntimeException peel(final Throwable t) { return (RuntimeException) peel(t, null, null, HAZELCAST_EXCEPTION_WRAPPER); }
@Test public void testPeel_whenThrowableIsExecutionExceptionWithCustomFactory_thenReturnCustomException() { IOException expectedException = new IOException(); RuntimeException result = (RuntimeException) ExceptionUtil.peel(new ExecutionException(expectedException), null, null, (throw...
@Override public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria) { Map<String, String> variables = new HashMap<>(); if (userRegex.isPresent()) { Matcher userMatcher = userRegex.get().matcher(criteria.getUser()); if (!userMatcher.matches()) { ...
@Test public void testSelectorResourceEstimate() { ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "foo"); StaticSelector smallQuerySelector = new StaticSelector( Optional.empty(), Optional.empty(), Optional.em...
@Override public String format(final Schema schema) { final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema); return options.contains(Option.AS_COLUMN_LIST) ? stripTopLevelStruct(converted) : converted; }
@Test public void shouldFormatOptionalStructAsColumns() { // Given: final Schema structSchema = SchemaBuilder.struct() .field("COL1", Schema.OPTIONAL_STRING_SCHEMA) .field("COL4", SchemaBuilder .array(Schema.OPTIONAL_FLOAT64_SCHEMA) .optional() .build()) ...
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed!"); return; } final List<ViewWidgetLimitMigration> widgetLimitMigrations = StreamSupport.stream(this.views.find().spliterator(),...
@Test @MongoDBFixtures("V20230113095300_MigrateGlobalPivotLimitsToGroupingsInViewsTest_empty.json") void notMigratingAnythingIfViewsAreEmpty() { this.migration.upgrade(); assertThat(migrationCompleted().migratedViews()).isZero(); }
void visit(final PathItem.HttpMethod method, final Operation operation, final PathItem pathItem) { if (filter.accept(operation.getOperationId())) { final String methodName = method.name().toLowerCase(); emitter.emit(methodName, path); emit("id", operation.getOperationId()); ...
@Test public void shouldEmitReferenceType() { final Builder method = MethodSpec.methodBuilder("configure"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method); final OperationVisitor<?> visitor = new OperationVisitor<>( emitter, new OperationF...
@Override public void execute(GraphModel graphModel) { Graph graph = graphModel.getGraphVisible(); execute(graph); }
@Test public void testColumnReplace() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1); graphModel.getNodeTable().addColumn(Degree.DEGREE, String.class); Degree d = new Degree(); d.execute(graphModel); }
@Override public T addInt(K name, int value) { throw new UnsupportedOperationException("read only"); }
@Test public void testAddInt() { assertThrows(UnsupportedOperationException.class, new Executable() { @Override public void execute() { HEADERS.addInt("name", 0); } }); }
@Override public Comparison compare(final Path.Type type, final PathAttributes local, final PathAttributes remote) { switch(type) { case directory: if(log.isDebugEnabled()) { log.debug(String.format("Compare local attributes %s with remote %s using %s", local,...
@Test public void testCompareSymlink() { final DefaultComparisonService c = new DefaultComparisonService(new TestProtocol()); assertEquals(Comparison.equal, c.compare(Path.Type.symboliclink, new PathAttributes().withModificationDate(1680879106939L), new PathAttributes().withModificationDate(16808791...
@Override public void onTaskFinished(TaskAttachment attachment) { if (attachment instanceof BrokerPendingTaskAttachment) { onPendingTaskFinished((BrokerPendingTaskAttachment) attachment); } else if (attachment instanceof BrokerLoadingTaskAttachment) { onLoadingTaskFinished((B...
@Test public void testLoadingTaskOnFinishedPartialUpdate(@Injectable BrokerPendingTaskAttachment attachment1, @Injectable LoadTask loadTask1, @Mocked GlobalStateMgr globalStateMgr, @Injectab...
@Override public String getString(final int columnIndex) throws SQLException { return (String) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, String.class), String.class); }
@Test void assertGetStringWithColumnLabel() throws SQLException { when(mergeResultSet.getValue(1, String.class)).thenReturn("value"); assertThat(shardingSphereResultSet.getString("label"), is("value")); }
@Override public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) { if (response.errorCode() != Errors.NONE.code()) { String errorMessage = String.format( "Unexpected error in Heartbeat response. Expected no error, but received: %s", Er...
@Test public void testUpdateStateFailsOnResponsesWithErrors() { ConsumerMembershipManager membershipManager = createMembershipManagerJoiningGroup(); // Updating state with a heartbeat response containing errors cannot be performed and // should fail. ConsumerGroupHeartbeatResponse un...
public NodeList findElementsAndTypes() throws XPathExpressionException { return (NodeList) xPath.compile("/xs:schema/xs:element") .evaluate(document, XPathConstants.NODESET); }
@Test public void testFindElementsAndTypes() throws Exception { Document document = XmlHelper.buildNamespaceAwareDocument( ResourceUtils.getResourceAsFile("xmls/3_elements.xml")); XPath xPath = XmlHelper.buildXPath(new CamelSpringNamespace()); domFinder = new DomFinder(docume...
static BlockStmt getConstantVariableDeclaration(final String variableName, final Constant constant) { final MethodDeclaration methodDeclaration = CONSTANT_TEMPLATE.getMethodsByName(GETKIEPMMLCONSTANT).get(0).clone(); final BlockStmt toReturn = methodDeclaration.getBody()....
@Test void getConstantVariableDeclaration() throws IOException { String variableName = "variableName"; Object value = 2342.21; Constant constant = new Constant(); constant.setValue(value); BlockStmt retrieved = KiePMMLConstantFactory.getConstantVariableDeclaration(variableNam...
static Long replicationThrottle(CruiseControlRequestContext requestContext, KafkaCruiseControlConfig config) { Long value = getLongParam(requestContext, REPLICATION_THROTTLE_PARAM, config.getLong(ExecutorConfig.DEFAULT_REPLICATION_THROTTLE_CONFIG)); if (value != null && value < 0) { throw new UserRequestE...
@Test public void testParseReplicationThrottleWithDefault() { CruiseControlRequestContext mockRequest = EasyMock.mock(CruiseControlRequestContext.class); KafkaCruiseControlConfig controlConfig = EasyMock.mock(KafkaCruiseControlConfig.class); // No parameter string value in the parameter map EasyMock.e...
@SuppressWarnings("unchecked") public <T> T convert(DocString docString, Type targetType) { if (DocString.class.equals(targetType)) { return (T) docString; } List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType); if (d...
@Test void json_to_string_with_registered_json_for_json_node_uses_default() { registry.defineDocStringType(jsonNodeForJson); DocString docString = DocString.create("hello world", "json"); assertThat(converter.convert(docString, String.class), is("hello world")); }
@Override public void stopThreads() { super.stopThreads(); try { if (tokenCache != null) { tokenCache.close(); } } catch (Exception e) { LOG.error("Could not stop Delegation Token Cache", e); } try { if (delTokSeqCounter != null) { delTokSeqCounter.close(); ...
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testStopThreads() throws Exception { DelegationTokenManager tm1 = null; String connectString = zkServer.getConnectString(); // let's make the update interval short and the shutdown interval // comparatively longer, so if the update th...
@Override public void updateDictType(DictTypeSaveReqVO updateReqVO) { // 校验自己存在 validateDictTypeExists(updateReqVO.getId()); // 校验字典类型的名字的唯一性 validateDictTypeNameUnique(updateReqVO.getId(), updateReqVO.getName()); // 校验字典类型的类型的唯一性 validateDictTypeUnique(updateReqVO.ge...
@Test public void testUpdateDictType_success() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 准备参数 DictTypeSaveReqVO reqVO = randomPojo(DictTypeSaveReqVO.class, o -> { o.setId(dbDictType.getId());...
static Map<String, Object> of(final Task task) { return Map.of( "id", task.getId(), "type", task.getType() ); }
@Test void shouldGetVariablesGivenTrigger() { Map<String, Object> variables = new RunVariables.DefaultBuilder() .withTrigger(new AbstractTrigger() { @Override public String getId() { return "id-value"; } @Overri...
@Override public OFAgent removeAgent(NetworkId networkId) { checkNotNull(networkId, ERR_NULL_NETID); synchronized (this) { OFAgent existing = ofAgentStore.ofAgent(networkId); if (existing == null) { final String error = String.format(MSG_OFAGENT, networkId, ER...
@Test(expected = IllegalStateException.class) public void testRemoveNotFoundAgent() { target.removeAgent(NETWORK_1); }
@Override @Deprecated public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier, final String... stateStoreNames) { Objects.requireNonNul...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowBadTransformerSupplierOnFlatTransform() { final org.apache.kafka.streams.kstream.Transformer<String, String, Iterable<KeyValue<String, String>>> transformer = flatTransformerSupplier.get(); final IllegalArgumentException exception ...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvEmpty() { CharSequence value = ""; escapeCsv(value, value); }
@Delete(uri = "{namespace}/{id}") @ExecuteOn(TaskExecutors.IO) @Operation(tags = {"Flows"}, summary = "Delete a flow") @ApiResponse(responseCode = "204", description = "On success") public HttpResponse<Void> delete( @Parameter(description = "The flow namespace") @PathVariable String namespace, ...
@Test void importFlowsWithZip() throws IOException { // create a ZIP file using the extract endpoint byte[] zip = client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/export/by-query?namespace=io.kestra.tests"), Argument.of(byte[].class)); File temp = File.createTempFile("...
long getTime() { return System.currentTimeMillis(); }
@Test (timeout=10000) public void testClock(){ Clock clock= new Clock(); long templateTime=System.currentTimeMillis(); long time=clock.getTime(); assertEquals(templateTime, time,30); }
@Override public Optional<FunctionDefinition> getFunctionDefinition(String name) { final String normalizedName = name.toUpperCase(Locale.ROOT); return Optional.ofNullable(normalizedFunctions.get(normalizedName)); }
@Test void testGetNonExistFunction() { assertThat(CoreModule.INSTANCE.getFunctionDefinition("nonexist")).isEmpty(); }
@Override @SuppressWarnings("nullness") public synchronized List<Map<String, Object>> runSQLQuery(String sql) { try (Statement stmt = driver.getConnection(getUri(), username, password).createStatement()) { List<Map<String, Object>> result = new ArrayList<>(); ResultSet resultSet = stmt.executeQuery(...
@Test public void testRunSQLStatementShouldNotThrowErrorIfJDBCDoesNotThrowAnyError() throws SQLException { when(container.getHost()).thenReturn(HOST); when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT); testManager.runSQLQuery("SQL statement"); verify(driver.getConnection(any(), ...
public static boolean isRuncContainerRequested(Configuration daemonConf, Map<String, String> env) { String type = (env == null) ? null : env.get(ContainerRuntimeConstants.ENV_CONTAINER_TYPE); if (type == null) { type = daemonConf.get(YarnConfiguration.LINUX_CONTAINER_RUNTIME_TYPE); } ...
@Test public void testSelectRuncContainerType() { Map<String, String> envRuncType = new HashMap<>(); Map<String, String> envOtherType = new HashMap<>(); envRuncType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, ContainerRuntimeConstants.CONTAINER_RUNTIME_RUNC); envOtherType.put(ContainerR...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testChronicleAddSingleChargeFull() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHRONICLE_ADD_SINGLE_CHARGE_FULL, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig....
public String build() { if (columnDefs.isEmpty()) { throw new IllegalStateException("No column has been defined"); } StringBuilder sql = new StringBuilder().append("ALTER TABLE ").append(tableName).append(" "); switch (dialect.getId()) { case PostgreSql.ID: addColumns(sql, "ADD COLU...
@Test public void add_columns_on_oracle() { assertThat(createSampleBuilder(new Oracle()).build()) .isEqualTo("ALTER TABLE issues ADD (date_in_ms NUMBER (38) NULL, name VARCHAR2 (10 CHAR) NOT NULL, col_with_default NUMBER(1) DEFAULT 0 NOT NULL, varchar_col_with_default VARCHAR2 (3 CHAR) DEFAULT 'foo' NOT NUL...
@PublicAPI(usage = ACCESS) public Set<Dependency> getDirectDependenciesFromSelf() { return javaClassDependencies.getDirectDependenciesFromClass(); }
@Test public void direct_dependencies_from_self_finds_correct_set_of_target_types() { JavaClass javaClass = importPackagesOf(getClass()).get(ClassWithAnnotationDependencies.class); Set<JavaClass> targets = javaClass.getDirectDependenciesFromSelf().stream().map(GET_TARGET_CLASS).collect(toSet()); ...
String buildUrl( JmsDelegate delegate, boolean debug ) { StringBuilder finalUrl = new StringBuilder( delegate.amqUrl.trim() ); // verify user hit the checkbox on the dialogue *and* also has not specified these values on the URL already // end result: default to SSL settings in the URL if present, otherwise...
@Test public void testUrlBuildSslOptionsNoSsl() { ActiveMQProvider provider = new ActiveMQProvider(); JmsDelegate delegate = new JmsDelegate( Collections.singletonList( provider ) ); delegate.amqUrl = AMQ_URL_BASE; delegate.sslEnabled = false; delegate.sslTruststorePath = TRUST_STORE_PATH_VAL; ...
@Override public TypeInformation<Tuple2<K, V>> getProducedType() { return new TupleTypeInfo<Tuple2<K, V>>( TypeExtractor.createTypeInfo(keyClass), TypeExtractor.createTypeInfo(valueClass)); }
@Test void checkTypeInformation() throws Exception { HadoopInputFormat<Void, Long> hadoopInputFormat = new HadoopInputFormat<>( new DummyVoidKeyInputFormat<Long>(), Void.class, Long.class, Job.ge...
public boolean include(NotificationFilter filter) { return pipelineName.equals(filter.pipelineName) && stageName.equals(filter.stageName) && event.include(filter.event); }
@Test void filterWithSameEventShouldIncludeOthers() { assertThat(new NotificationFilter("cruise", "dev", StageEvent.Fixed, false).include( new NotificationFilter("cruise", "dev", StageEvent.Fixed, true))).isTrue(); }
@Override public NacosLoggingAdapter build() { return new LogbackNacosLoggingAdapter(); }
@Test void build() { LogbackNacosLoggingAdapterBuilder builder = new LogbackNacosLoggingAdapterBuilder(); NacosLoggingAdapter adapter = builder.build(); assertNotNull(adapter); assertTrue(adapter instanceof LogbackNacosLoggingAdapter); }
@Override public void removeAllVpls() { Set<VplsData> allVplses = ImmutableSet.copyOf(vplsStore.getAllVpls()); allVplses.forEach(this::removeVpls); }
@Test public void testRemoveAllVpls() { VplsData vplsData = VplsData.of(VPLS1); vplsData.state(ADDED); vplsStore.addVpls(vplsData); vplsData = VplsData.of(VPLS2, VLAN); vplsData.state(ADDED); vplsStore.addVpls(vplsData); vplsManager.removeAllVpls(); ...
public void addNote(Note note, AuthenticationInfo subject) throws IOException { addOrUpdateNoteNode(new NoteInfo(note), true); noteCache.putNote(note); }
@Test void testAddNoteRejectsDuplicatePath() throws IOException { assertThrows(NotePathAlreadyExistsException.class, () -> { Note note1 = createNote("/prod/note"); Note note2 = createNote("/prod/note"); noteManager.addNote(note1, AuthenticationInfo.ANONYMOUS...
public ConnectionAuthContext authorizePeer(X509Certificate cert) { return authorizePeer(List.of(cert)); }
@Test void auth_context_contains_union_of_granted_capabilities_from_policies() { RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn"); RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san"); PeerAuthorizer peerAuthorizer =...
public int getDepth() { String path = mUri.getPath(); if (path.isEmpty() || CUR_DIR.equals(path)) { return 0; } if (hasWindowsDrive(path, true)) { path = path.substring(3); } int depth = 0; int slash = path.length() == 1 && path.charAt(0) == '/' ? -1 : 0; while (slash != -1...
@Test public void getDepthTests() { assertEquals(0, new AlluxioURI("").getDepth()); assertEquals(0, new AlluxioURI(".").getDepth()); assertEquals(0, new AlluxioURI("/").getDepth()); assertEquals(1, new AlluxioURI("/a").getDepth()); assertEquals(3, new AlluxioURI("/a/b/c.txt").getDepth()); asse...
public JunctionTree junctionTree(List<OpenBitSet> cliques, boolean init) { return junctionTree(null, null, null, cliques, init); }
@Test public void testJunctionWithPruning1() { Graph<BayesVariable> graph = new BayesNetwork(); GraphNode x0 = addNode(graph); GraphNode x1 = addNode(graph); GraphNode x2 = addNode(graph); GraphNode x3 = addNode(graph); GraphNode x4 = addNode(graph); GraphNode...
@Override public Optional<OffsetExpirationCondition> offsetExpirationCondition() { throw new UnsupportedOperationException("offsetExpirationCondition is not supported for Share Groups."); }
@Test public void testOffsetExpirationCondition() { ShareGroup shareGroup = createShareGroup("group-foo"); assertThrows(UnsupportedOperationException.class, shareGroup::offsetExpirationCondition); }
@Override public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) { StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES"); String[] queryParams = null; switch (scope.type()) { case ROOT: // account-level listing baseQuery.append(" IN ACCOUNT"); ...
@SuppressWarnings("unchecked") @Test public void testListIcebergTablesInterruptedException() throws SQLException, InterruptedException { Exception injectedException = new InterruptedException("Fake interrupted exception"); when(mockClientPool.run(any(ClientPool.Action.class))).thenThrow(injectedExcept...
public ConfigResponse resolveConfig(GetConfigRequest req, ConfigResponseFactory responseFactory) { long start = System.currentTimeMillis(); metricUpdater.incrementRequests(); ConfigKey<?> configKey = req.getConfigKey(); String defMd5 = req.getRequestDefMd5(); if (defMd5 == null |...
@Test(expected = UnknownConfigDefinitionException.class) public void require_that_def_file_must_exist() { handler.resolveConfig(createRequest("unknown", "namespace", emptySchema)); }
@Override @Nonnull public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) { throwRejectedExecutionExceptionIfShutdown(); ArrayList<Future<T>> result = new ArrayList<>(); for (Callable<T> task : tasks) { try { result.add(new Co...
@Test void testRejectedInvokeAnyWithTimeout() { testRejectedExecutionException( testInstance -> testInstance.invokeAll( Collections.singleton(() -> null), 1L, TimeUnit.DAYS)); }
public static Setting getFirstFound(String... names) { for (String name : names) { try { return get(name); } catch (NoResourceException e) { //ignore } } return null; }
@Test public void getFirstFoundTest() { //noinspection ConstantConditions String driver = SettingUtil.getFirstFound("test2", "test") .get("demo", "driver"); assertEquals("com.mysql.jdbc.Driver", driver); }
public static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0x1D0F, data, offset, length, false, false, 0x0000); }
@Test public void AUG_CCITT_A() { final byte[] data = new byte[] { 'A' }; assertEquals(0x9479, CRC16.AUG_CCITT(data, 0, 1)); }
public static List<ConsumerGroupMemberMetadataValue.ClassicProtocol> classicProtocolListFromJoinRequestProtocolCollection( JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols ) { List<ConsumerGroupMemberMetadataValue.ClassicProtocol> newSupportedProtocols = new ArrayList<>(); p...
@Test public void testClassicProtocolListFromJoinRequestProtocolCollection() { JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestData.JoinGroupRequestProtocolCollection(); protocols.addAll(Arrays.asList( new JoinGroupRequestData.JoinGroupRequestProto...