focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Description("Laplace cdf given mean, scale parameters and value") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double laplaceCdf( @SqlType(StandardTypes.DOUBLE) double mean, @SqlType(StandardTypes.DOUBLE) double scale, @SqlType(StandardTypes.DOUBLE) doubl...
@Test public void testLaplaceCdf() { assertFunction("laplace_cdf(4, 1, 4)", DOUBLE, 0.5); assertFunction("laplace_cdf(4, 2, 4.0)", DOUBLE, 0.5); assertFunction("round(laplace_cdf(4, 2, 4.0 - 0.4463), 2)", DOUBLE, 0.4); assertFunction("round(laplace_cdf(-4, 2, -4.0 + 0.4463), 4)",...
protected static String formatMemory(long bytes) { return Long.toString(bytes); }
@Test public void testFormatMemory() { assertThat(formatMemory(0), is("0")); assertThat(formatMemory(1), is("1")); assertThat(formatMemory(1023), is("1023")); assertThat(formatMemory(1024), is("1024")); assertThat(formatMemory(1000), is("1000")); assertThat(formatMemo...
public static void setKiePMMLConstructorSuperNameInvocation(final String generatedClassName, final ConstructorDeclaration constructorDeclaration, final String fileName, ...
@Test void setKiePMMLConstructorSuperNameInvocation() { String generatedClassName = "generatedClassName"; String fileName = "fileName"; String name = "newName"; org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.setKiePMMLConstructorSuperNameInvocation(generatedC...
void backoff(int attempt, long deadline) { int numRetry = attempt - 1; long delay = RETRIES_DELAY_MIN_MS << numRetry; if (delay > errorMaxDelayInMillis) { delay = ThreadLocalRandom.current().nextLong(errorMaxDelayInMillis); } long currentTime = time.milliseconds(); ...
@Test public void testBackoffLimit() throws Exception { MockTime time = new MockTime(0, 0, 0); CountDownLatch exitLatch = mock(CountDownLatch.class); RetryWithToleranceOperator<ConsumerRecord<byte[], byte[]>> retryWithToleranceOperator = new RetryWithToleranceOperator<>(5, 5000, NONE, time, ...
@Override public boolean match(Message msg, StreamRule rule) { Object rawField = msg.getField(rule.getField()); if (rawField == null) { return rule.getInverted(); } if (rawField instanceof String) { String field = (String) rawField; Boolean resul...
@Test public void testBasicMatch() throws Exception { StreamRule rule = getSampleRule(); rule.setField("message"); rule.setType(StreamRuleType.PRESENCE); rule.setInverted(false); Message message = getSampleMessage(); StreamRuleMatcher matcher = getMatcher(rule); ...
public java.nio.file.Path toPath(final Path file) throws LocalAccessDeniedException { return this.toPath(file.getAbsolute()); }
@Test public void toPath() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()); ...
public static void updateTableStatsForCreateTable(Warehouse wh, Database db, Table tbl, EnvironmentContext envContext, Configuration conf, Path tblPath, boolean newDir) throws MetaException { // If the created table is a view, skip generating the stats if (MetaStoreUtils.isView(tbl)) { return;...
@Test public void testUpdateTableStatsForCreateTableDoesNotInvokeStatsCalc() throws TException { // DO_NOT_UPDATE_STATS in env context is set to true => doesn't invoke stats calculation Map<String, String> params = new HashMap<>(paramsWithStats); Warehouse wh = mock(Warehouse.class); Table tbl = new ...
protected static Map<String, String> parsePostHeaders(InputStream in) throws IOException { Map<String, String> headerMap = new HashMap<String, String>(4); String line; while (true) { line = readLine(in); if (line == null || line.length() == 0) { // empty l...
@Test public void parsePostHeaders() throws IOException { Map<String, String> map; map = HttpEventTask.parsePostHeaders(new ByteArrayInputStream("".getBytes())); assertTrue(map.size() == 0); map = HttpEventTask.parsePostHeaders(new ByteArrayInputStream("Content-type...
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData, TypeReference<T> responseFormat) { return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null); }
@Test public void testStatusCodeAndErrorMessagePreserved() throws Exception { int statusCode = Response.Status.CONFLICT.getStatusCode(); ErrorMessage errorMsg = new ErrorMessage(Response.Status.GONE.getStatusCode(), "Some Error Message"); Request req = mock(Request.class); ContentRes...
public HeaderConverter newHeaderConverter(AbstractConfig config, String classPropertyName, ClassLoaderUsage classLoaderUsage) { Class<? extends HeaderConverter> klass = null; switch (classLoaderUsage) { case CURRENT_CLASSLOADER: if (!config.originals().containsKey(classProper...
@Test public void shouldInstantiateAndConfigureDefaultHeaderConverter() { props.remove(WorkerConfig.HEADER_CONVERTER_CLASS_CONFIG); createConfig(); // Because it's not explicitly set on the supplied configuration, the logic to use the current classloader for the connector // will ex...
@Bean public ShenyuPlugin contextPathPlugin() { return new ContextPathPlugin(); }
@Test public void testContextPathPlugin() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ContextPathPluginConfiguration.class)) .withBean(ContextPathPluginConfigurationTest.class) .withPropertyValues("debug=true") .run(context -> { ...
@Override public void run() { try { interceptorChain.doInterceptor(task); } catch (Exception e) { Loggers.SRV_LOG.info("Interceptor health check task {} failed", task.getTaskId(), e); } }
@Test void testRunWithDisableHealthCheck() { when(switchDomain.isHealthCheckEnabled()).thenReturn(false); taskWrapper.run(); verify(distroMapper, never()).responsible(client.getResponsibleId()); }
@Override public final long skip(long n) { if (n <= 0 || n >= Integer.MAX_VALUE) { return 0L; } return skipBytes((int) n); }
@Test public void testSkip() { long s1 = in.skip(-1); long s2 = in.skip(Integer.MAX_VALUE); long s3 = in.skip(1); assertEquals(0, s1); assertEquals(0, s2); assertEquals(1, s3); }
static Counter allocateErrorCounter( final Aeron aeron, final MutableDirectBuffer tempBuffer, final long archiveId) { int index = 0; tempBuffer.putLong(index, archiveId); index += SIZE_OF_LONG; final int keyLength = index; index += tempBuffer.putStrin...
@Test void allocateErrorCounter() { final long archiveId = 24623864; final String expectedLabel = "Archive Errors - archiveId=" + archiveId + " " + AeronCounters.formatVersionInfo(ArchiveVersion.VERSION, ArchiveVersion.GIT_SHA); final Aeron aeron = mock(Aeron.class); ...
public static boolean isInvalidPort(int port) { return port < MIN_PORT || port > MAX_PORT; }
@Test void testIsInvalidPort() { assertTrue(NetUtils.isInvalidPort(0)); assertTrue(NetUtils.isInvalidPort(65536)); assertFalse(NetUtils.isInvalidPort(1024)); }
public CreateTableBuilder withPkConstraintName(String pkConstraintName) { this.pkConstraintName = validateConstraintName(pkConstraintName); return this; }
@Test public void withPkConstraintName_throws_NPE_if_name_is_null() { assertThatThrownBy(() -> underTest.withPkConstraintName(null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Constraint name can't be null"); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof NiciraNshMdType) { NiciraNshMdType that = (NiciraNshMdType) obj; return Objects.equals(nshMdType, that.nshMdType); } return false; }
@Test public void testEquals() { final NiciraNshMdType nshMdType1 = new NiciraNshMdType(mdType1); final NiciraNshMdType sameAsnshMdType1 = new NiciraNshMdType(mdType1); final NiciraNshMdType nshMdType2 = new NiciraNshMdType(mdType2); new EqualsTester().addEqualityGroup(nshMdType1, s...
@Override protected void render(Block html) { String jid = $(JOB_ID); if (jid.isEmpty()) { html. p().__("Sorry, can't do anything without a JobID.").__(); return; } JobId jobID = MRApps.toJobID(jid); Job j = appContext.getJob(jobID); if (j == null) { html.p().__("Sorry,...
@Test public void testHsJobBlockForOversizeJobShouldDisplayWarningMessage() { int maxAllowedTaskNum = 100; Configuration config = new Configuration(); config.setInt(JHAdminConfig.MR_HS_LOADED_JOBS_TASKS_MAX, maxAllowedTaskNum); JobHistory jobHistory = new JobHistoryStubWithAllOversizeJobs(ma...
@Override public MavenArtifact searchSha1(String sha1) throws IOException { if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) { throw new IllegalArgumentException("Invalid SHA1 format"); } final List<MavenArtifact> collectedMatchingArtifacts = new ArrayList<>(1); ...
@Test(expected = IllegalArgumentException.class) @Ignore public void testMalformedSha1() throws Exception { searcher.searchSha1("invalid"); }
public List<CodegenColumnDO> buildColumns(Long tableId, List<TableField> tableFields) { List<CodegenColumnDO> columns = CodegenConvert.INSTANCE.convertList(tableFields); int index = 1; for (CodegenColumnDO column : columns) { column.setTableId(tableId); column.setOrdinalP...
@Test public void testBuildColumns() { // 准备参数 Long tableId = randomLongId(); TableField tableField = mock(TableField.class); List<TableField> tableFields = Collections.singletonList(tableField); // mock 方法 TableField.MetaInfo metaInfo = mock(TableField.MetaInfo.class...
public boolean match(int left, int right) { return left == right; }
@Test public void intShouldEqual() { int a = 334; int b = 334; boolean match = new NumberMatch().match(a, b); assertTrue(match); a = -123; b = -123; match = new NumberMatch().match(a, b); assertTrue(match); a = -122; b = -123; ...
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test public void testEqualityIPv4() { new EqualsTester() .addEqualityGroup(IpPrefix.valueOf("1.2.0.0/24"), IpPrefix.valueOf("1.2.0.0/24"), IpPrefix.valueOf("1.2.0.4/24")) .addEqualityGroup(IpPrefix.valueOf("1.2.0.0/16"), ...
static SortKey[] rangeBounds( int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) { // sort the keys first Arrays.sort(samples, comparator); int numCandidates = numPartitions - 1; SortKey[] candidates = new SortKey[numCandidates]; int step = (int) Math.ceil((double) sample...
@Test public void testRangeBoundsNonDivisible() { // step is 3 = ceiling(11/4) assertThat( SketchUtil.rangeBounds( 4, SORT_ORDER_COMPARTOR, new SortKey[] { CHAR_KEYS.get("a"), CHAR_KEYS.get("b"), ...
public void lockClusterState(ClusterStateChange stateChange, Address initiator, UUID txnId, long leaseTime, int memberListVersion, long partitionStateStamp) { Preconditions.checkNotNull(stateChange); clusterServiceLock.lock(); try { if (!node.getNodeE...
@Test(expected = NullPointerException.class) public void test_lockClusterState_nullState() throws Exception { Address initiator = newAddress(); clusterStateManager.lockClusterState(null, initiator, TXN, 1000, MEMBERLIST_VERSION, PARTITION_STAMP); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void deleteMyCommands() { DeleteMyCommands cmds = new DeleteMyCommands(); cmds.languageCode("en"); cmds.scope(new BotCommandScopeAllChatAdministrators()); BaseResponse response = bot.execute(cmds); assertTrue(response.isOk()); GetMyCommands getCmds = ne...
void prioritizeCopiesAndShiftUps(List<MigrationInfo> migrations) { for (int i = 0; i < migrations.size(); i++) { prioritize(migrations, i); } if (logger.isFinestEnabled()) { StringBuilder s = new StringBuilder("Migration order after prioritization: ["); int i...
@Test public void testNoCopyPrioritizationAgainstCopy() throws UnknownHostException { List<MigrationInfo> migrations = new ArrayList<>(); final MigrationInfo migration1 = new MigrationInfo(0, null, new PartitionReplica(new Address("localhost", 5701), uuids[0]), -1, -1, -1, 0); final Migratio...
public boolean setSeverity(DefaultIssue issue, String severity, IssueChangeContext context) { checkState(!issue.manualSeverity(), "Severity can't be changed"); if (!Objects.equals(severity, issue.severity())) { issue.setFieldChange(context, SEVERITY, issue.severity(), severity); issue.setSeverity(se...
@Test void set_severity() { boolean updated = underTest.setSeverity(issue, "BLOCKER", context); assertThat(updated).isTrue(); assertThat(issue.severity()).isEqualTo("BLOCKER"); assertThat(issue.manualSeverity()).isFalse(); assertThat(issue.mustSendNotifications()).isFalse(); FieldDiffs.Diff d...
@Override public boolean contains(final Object value) { return value instanceof Long l && contains(l.longValue()); }
@Test public void initiallyContainsNoBoxedElements() { for (int i = 0; i < 10000; i++) { assertFalse(set.contains(Long.valueOf(i))); } }
@ScalarOperator(MODULUS) @SqlType(StandardTypes.REAL) public static long modulus(@SqlType(StandardTypes.REAL) long left, @SqlType(StandardTypes.REAL) long right) { return floatToRawIntBits(intBitsToFloat((int) left) % intBitsToFloat((int) right)); }
@Test public void testModulus() { assertFunction("REAL'12.34' % REAL'56.78'", REAL, 12.34f % 56.78f); assertFunction("REAL'-17.34' % REAL'-22.891'", REAL, -17.34f % -22.891f); assertFunction("REAL'-89.123' % REAL'754.0'", REAL, -89.123f % 754.0f); assertFunction("REAL'-0.0' % REA...
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) { return drlxParse(patternType, bindingId, expression, false); }
@Test public void testNullSafeExpressionsWithOr() { SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "name == \"John\" || == address!.city"); assertThat(result.getNullSafeExpressions().size()).isEqualTo(0); // not using NullSafeExpressions for complex OR...
public void stop() { if (stopped) { return; } if (executor != null) { synchronized (executor) { stopped = true; executor.shutdown(); } } SPAS_LOGGER.info("[{}] {} is stopped", appName, this.getClass().getSimpleNa...
@Test void testStop() throws NoSuchFieldException, IllegalAccessException { credentialWatcher.stop(); Field executorField = CredentialWatcher.class.getDeclaredField("executor"); executorField.setAccessible(true); ScheduledExecutorService executor = (ScheduledExecutorService) executor...
@Override public RecordSet getRecordSet(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorSplit split, List<? extends ColumnHandle> columns) { JdbcSplit jdbcSplit = (JdbcSplit) split; ImmutableList.Builder<JdbcColumnHandle> handles = ImmutableList.builder(); ...
@Test public void testGetRecordSet() { ConnectorTransactionHandle transaction = new JdbcTransactionHandle(); JdbcRecordSetProvider recordSetProvider = new JdbcRecordSetProvider(jdbcClient); RecordSet recordSet = recordSetProvider.getRecordSet(transaction, SESSION, split, ImmutableList.of...
public String convert(ILoggingEvent le) { long timestamp = le.getTimeStamp(); return cachingDateFormatter.format(timestamp); }
@Test public void convertsDateInSpecifiedTimeZoneAsGmtOffset() { assertEquals(formatDate("GMT-8"), convert(_timestamp, DATETIME_PATTERN, "GMT-8")); }
NewCookie createAuthenticationCookie(SessionResponse token, ContainerRequestContext requestContext) { return makeCookie(token.getAuthenticationToken(), token.validUntil(), requestContext); }
@Test void safePath() { containerRequest.getHeaders().put(HttpConfiguration.OVERRIDE_HEADER, List.of("http://graylog.local/path/;authentication=overridden-auth-value;")); final CookieFactory cookieFactory = new CookieFactory(new HttpConfiguration()); final NewCookie cookie =...
@Override @SuppressWarnings("unchecked") public <A extends ThreadPoolPlugin> Optional<A> getPlugin(String pluginId) { return mainLock.applyWithReadLock( () -> (Optional<A>) Optional.ofNullable(registeredPlugins.get(pluginId))); }
@Test public void testGetPlugin() { ThreadPoolPlugin plugin = new TestExecuteAwarePlugin(); manager.register(plugin); Assert.assertSame(plugin, manager.getPlugin(plugin.getId()).orElse(null)); }
@VisibleForTesting public SmsChannelDO validateSmsChannel(Long channelId) { SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId); if (channelDO == null) { throw exception(SMS_CHANNEL_NOT_EXISTS); } if (CommonStatusEnum.isDisable(channelDO.getStatus())) { ...
@Test public void testValidateSmsChannel_success() { // 准备参数 Long channelId = randomLongId(); // mock 方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(channelId); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于...
@Override public PropertySource<?> locate(Environment environment) { if (polarisConfigProperties.isEnabled()) { CompositePropertySource compositePropertySource = new CompositePropertySource(POLARIS_CONFIG_PROPERTY_SOURCE_NAME); try { // load custom config extension files initCustomPolarisConfigExtensio...
@Test public void testGetCustomFiles() { PolarisConfigFileLocator locator = new PolarisConfigFileLocator(polarisConfigProperties, polarisContextProperties, configFileService, environment); when(polarisContextProperties.getNamespace()).thenReturn(testNamespace); when(polarisContextProperties.getService()).th...
public void onNewMetadataImage(MetadataImage newImage, MetadataDelta delta) { metadataImage = newImage; // Notify all the groups subscribed to the created, updated or // deleted topics. Optional.ofNullable(delta.topicsDelta()).ifPresent(topicsDelta -> { Set<String> allGroupI...
@Test public void testOnNewMetadataImage() { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroupAssignors(Collections.singletonList(new MockPartitionAssignor("range"))) .build(); // M1 in group 1 subscribes to a and b. ...
public static int[] computePhysicalIndices( List<TableColumn> logicalColumns, DataType physicalType, Function<String, String> nameRemapping) { Map<TableColumn, Integer> physicalIndexLookup = computePhysicalIndices(logicalColumns.stream(), physicalType, nameRe...
@Test void testFieldMappingRowTypeNotMatchingTypesInNestedType() { assertThatThrownBy( () -> TypeMappingUtils.computePhysicalIndices( TableSchema.builder() .field("...
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 testNamespaceHasNoNormalItemsAndRelease() { long namespaceId = 1; Namespace namespace = createNamespace(namespaceId); when(releaseService.findLatestActiveRelease(namespace)).thenReturn(null); when(itemService.findItemsWithoutOrdered(namespaceId)).thenReturn(Collections.singletonLis...
@Override public List<TransferItem> list(final Session<?> session, final Path directory, final Local local, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List children for %s", directory));...
@Test public void testRegexFilter() throws Exception { final Path parent = new Path("t", EnumSet.of(Path.Type.directory)); final Transfer t = new DownloadTransfer(new Host(new TestProtocol()), parent, new NullLocal(System.getProperty("java.io.tmpdir"))); final NullSession session = new NullS...
@ProtoFactory public static MediaType fromString(String tree) { if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType(); Matcher matcher = TREE_PATTERN.matcher(tree); return parseSingleMediaType(tree, matcher, false); }
@Test public void testUnquotedParamWithSingleQuote() { MediaType mediaType = MediaType.fromString("application/json; charset='UTF-8'"); assertMediaTypeWithParam(mediaType, "application", "json", "charset", "'UTF-8'"); Exceptions.expectException(EncodingException.class, () -> MediaType.fromString("...
@Override @Deprecated public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier, final String... stateStoreNames) { process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames); }
@Test public void shouldNotAllowNullNamedOnProcess() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.process(processorSupplier, (Named) null)); assertThat(exception.getMessage(), equalTo("named can't be null")); }
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoun...
@Test public void callingMethodReturningDoubleShouldInvokeClassHandler() throws Exception { Class<?> exampleClass = loadClass(AClassWithMethodReturningDouble.class); classHandler.valueToReturn = 456; Method normalMethod = exampleClass.getMethod("normalMethodReturningDouble", double.class); Object exa...
@Override public String toString() { return String.format("Repeatedly.forever(%s)", subTriggers.get(REPEATED)); }
@Test public void testToString() { Trigger trigger = Repeatedly.forever( new StubTrigger() { @Override public String toString() { return "innerTrigger"; } }); assertEquals("Repeatedly.forever(innerTrigger)", trigger.toS...
public TExecPlanFragmentParams plan(TUniqueId loadId) throws UserException { boolean isPrimaryKey = destTable.getKeysType() == KeysType.PRIMARY_KEYS; resetAnalyzer(); // construct tuple descriptor, used for scanNode and dataSink TupleDescriptor tupleDesc = descTable.createTupleDescriptor...
@Test public void testNormalPlan() throws UserException { List<Column> columns = Lists.newArrayList(); Column c1 = new Column("c1", Type.BIGINT, false); columns.add(c1); Column c2 = new Column("c2", Type.BIGINT, true); columns.add(c2); new Expectations() { ...
@Override public void run() { // top-level command, do nothing }
@Test public void test_restartJob_invalidNameOrId() { // When // Then exception.expectMessage("No job with name or id 'invalid' was found"); run("restart", "invalid"); }
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) { if (list == null) { return FEELFnResult.ofResult(true); } boolean result = true; for (final Object element : list) { if (element != null && !(element instanceof Boolean)) { ret...
@Test void invokeBooleanParamNull() { FunctionTestUtil.assertResult(nnAllFunction.invoke((Boolean) null), true); }
public static ConfigInfos generateResult(String connType, Map<String, ConfigKey> configKeys, List<ConfigValue> configValues, List<String> groups) { int errorCount = 0; List<ConfigInfo> configInfoList = new LinkedList<>(); Map<String, ConfigValue> configValueMap = new HashMap<>(); for (C...
@Test public void testGenerateResultWithConfigValuesWithNoConfigKeysAndWithSomeErrors() { String name = "com.acme.connector.MyConnector"; Map<String, ConfigDef.ConfigKey> keys = new HashMap<>(); List<String> groups = new ArrayList<>(); List<ConfigValue> values = new ArrayList<>(); ...
public LineReaders getLineReaders(Component component) { List<LineReader> readers = new ArrayList<>(); List<CloseableIterator<?>> closeables = new ArrayList<>(); ScmLineReader scmLineReader = null; int componentRef = component.getReportAttributes().getRef(); CloseableIterator<ScannerReport.LineCove...
@Test public void should_create_readers() { initBasicReport(10); LineReadersImpl lineReaders = (LineReadersImpl) underTest.getLineReaders(fileComponent()); assertThat(lineReaders).isNotNull(); assertThat(lineReaders.closeables).hasSize(3); assertThat(lineReaders.readers).hasSize(5); }
@Deprecated public Authentication getAuthentication(String token) throws AccessException { NacosUser nacosUser = jwtParser.parse(token); List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.EMPTY); User principal = new User(nac...
@Test void getAuthentication() throws AccessException { String nacosToken = jwtTokenManager.createToken("nacos"); Authentication authentication = jwtTokenManager.getAuthentication(nacosToken); assertNotNull(authentication); }
@Override public KeyValueIterator<Windowed<K>, V> fetch(final K key) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType); for (final ReadOnlySessionStore<K, V> store : stores) { tr...
@Test public void shouldFetchKeyRangeAcrossStoresWithNullKeyTo() { final ReadOnlySessionStoreStub<String, Long> secondUnderlying = new ReadOnlySessionStoreStub<>(); stubProviderTwo.addStore(storeName, secondUnderlying); underlyingSessionStore.put(new Windowed<>("a", new SessionWi...
public ConfigDescriptor getConfigDescriptor(Config configurationProxy) { Class<?> inter = configurationProxy.getClass().getInterfaces()[0]; ConfigGroup group = inter.getAnnotation(ConfigGroup.class); if (group == null) { throw new IllegalArgumentException("Not a config group"); } final List<ConfigSect...
@Test public void testGetConfigDescriptor() throws IOException { TestConfig conf = manager.getConfig(TestConfig.class); ConfigDescriptor descriptor = manager.getConfigDescriptor(conf); Assert.assertEquals(2, descriptor.getItems().size()); }
public int currentSdkClientCount() { Map<String, String> filter = new HashMap<>(2); filter.put(RemoteConstants.LABEL_SOURCE, RemoteConstants.LABEL_SOURCE_SDK); return currentClientsCount(filter); }
@Test void testCurrentSdkCount() { assertEquals(1, connectionManager.currentSdkClientCount()); }
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof JobMeta ) ) { return feedback; } JobMeta jobMeta = (JobMeta) subject; String description = jobMeta.getDesc...
@Test public void testVerifyRule_NullParameter_EnabledRule() { JobHasDescriptionImportRule importRule = getImportRule( 10, true ); List<ImportValidationFeedback> feedbackList = importRule.verifyRule( null ); assertNotNull( feedbackList ); assertTrue( feedbackList.isEmpty() ); }
@Override protected void processOptions(LinkedList<String> args) throws IOException { CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE, OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN, OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE, OPTION_MTIME, OPTION_SIZE, OPTION_A...
@Test public void processPathDirOrderMtime() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile(...
@Nullable @SuppressWarnings("checkstyle:returncount") static Metadata resolve(InternalSerializationService ss, Object target, boolean key) { try { if (target instanceof Data) { Data data = (Data) target; if (data.isPortable()) { ClassDefini...
@Test public void test_compactRecord() { SerializationConfig serializationConfig = new SerializationConfig(); InternalSerializationService ss = new DefaultSerializationServiceBuilder() .setSchemaService(CompactTestUtil.createInMemorySchemaService()) .setConfig(seriali...
public static Map<String, Object> coerceTypes( final Map<String, Object> streamsProperties, final boolean ignoreUnresolved ) { if (streamsProperties == null) { return Collections.emptyMap(); } final Map<String, Object> validated = new HashMap<>(streamsProperties.size()); for (final ...
@Test public void shouldThrowOnUnkownPropertyFromCoerceTypes() { // given/when: assertThrows( PropertyNotFoundException.class, () -> PropertiesUtil.coerceTypes(ImmutableMap.of("foo", "bar"), false) ); }
public static <K, V> Map<K, V> renameKey(Map<K, V> map, K oldKey, K newKey) { if (isNotEmpty(map) && map.containsKey(oldKey)) { if (map.containsKey(newKey)) { throw new IllegalArgumentException(StrUtil.format("The key '{}' exist !", newKey)); } map.put(newKey, map.remove(oldKey)); } return map; }
@Test public void renameKeyTest() { final Dict v1 = Dict.of().set("id", 12).set("name", "张三").set("age", null); final Map<String, Object> map = MapUtil.renameKey(v1, "name", "newName"); assertEquals("张三", map.get("newName")); }
@Override public TimeUnit unit() { return timeUnit; }
@Test public void nameAndUnit() { DefaultTimer timer = new DefaultTimer(TimeUnit.MINUTES); assertThat(timer.unit()).isEqualTo(TimeUnit.MINUTES); assertThat(timer.isNoop()).isFalse(); }
public static <T> Global<T> globally() { return new Global<>(); }
@Test @Category(NeedsRunner.class) public void testGroupGlobally() { Collection<Basic> elements = ImmutableList.of( Basic.of("key1", 1, "value1"), Basic.of("key1", 1, "value2"), Basic.of("key2", 2, "value3"), Basic.of("key2", 2, "value4")); PCollectio...
@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 WindowRangeQuery<GenericKey, GenericRow> query = WindowR...
@Test public void shouldReturnValueIfSessionStartsAtLowerBoundIfLowerStartBoundClosed() { // Given: final Range<Instant> startBounds = Range.closed( LOWER_INSTANT, UPPER_INSTANT ); final Instant wend = LOWER_INSTANT.plusMillis(1); givenSingleSession(LOWER_INSTANT, wend); // When:...
public ContentPackInstallation installContentPack(ContentPack contentPack, Map<String, ValueReference> parameters, String comment, String user) { if (...
@Test public void installContentPackWithSystemStreamDependencies() throws Exception { ImmutableSet<Entity> entities = ImmutableSet.of(createTestViewEntity(), createTestEventDefinitionEntity()); ContentPackV1 contentPack = ContentPackV1.builder() .description("test") ....
static AggregationStrategy createAggregationStrategy(CamelContext camelContext, DynamicRouterConfiguration cfg) { AggregationStrategy strategy = Optional.ofNullable(cfg.getAggregationStrategyBean()) .or(() -> Optional.ofNullable(cfg.getAggregationStrategy()) .map(ref -> l...
@Test void testCreateAggregationStrategyWithInstance() { when(mockConfig.getAggregationStrategyBean()).thenReturn(mockStrategy); AggregationStrategy strategy = DynamicRouterRecipientListHelper.createAggregationStrategy(camelContext, mockConfig); Assertions.assertNotNull(strategy); }
@Override public void run(DiagnosticsLogWriter writer) { writer.startSection("HazelcastInstance"); writer.writeKeyValueEntry("thisAddress", nodeEngine.getNode().getThisAddress().toString()); writer.writeKeyValueEntry("isRunning", nodeEngine.getNode().isRunning()); writer.writeKeyVal...
@Test public void testRun() { plugin.run(logWriter); assertContains("HazelcastInstance["); assertContains("isRunning=true"); assertContains("Members["); }
@Override public <VR> KTable<Windowed<K>, VR> aggregate(final Initializer<VR> initializer, final Aggregator<? super K, ? super V, VR> aggregator) { return aggregate(initializer, aggregator, Materialized.with(keySerde, null)); }
@Test public void shouldThrowNullPointerOnMaterializedAggregateIfAggregatorIsNull() { assertThrows(NullPointerException.class, () -> windowedStream.aggregate( MockInitializer.STRING_INIT, null, Materialized.as("store"))); }
@Override public void sendSmsCode(SmsCodeSendReqDTO reqDTO) { SmsSceneEnum sceneEnum = SmsSceneEnum.getCodeByScene(reqDTO.getScene()); Assert.notNull(sceneEnum, "验证码场景({}) 查找不到配置", reqDTO.getScene()); // 创建验证码 String code = createSmsCode(reqDTO.getMobile(), reqDTO.getScene(), reqDTO....
@Test public void sendSmsCode_tooFast() { // mock 数据 SmsCodeDO smsCodeDO = randomPojo(SmsCodeDO.class, o -> o.setMobile("15601691300").setTodayIndex(1)); smsCodeMapper.insert(smsCodeDO); // 准备参数 SmsCodeSendReqDTO reqDTO = randomPojo(SmsCodeSendReqDTO.class, o ...
public static CloudName from(String cloud) { return switch (cloud) { case "aws" -> AWS; case "azure" -> AZURE; case "gcp" -> GCP; case "default" -> DEFAULT; case "yahoo" -> YAHOO; default -> new CloudName(cloud); }; }
@Test void returns_same_instance_for_known_clouds() { assertSame(CloudName.from("aws"), CloudName.AWS); assertSame(CloudName.from("azure"), CloudName.AZURE); assertSame(CloudName.from("gcp"), CloudName.GCP); assertSame(CloudName.from("default"), CloudName.DEFAULT); assertSame...
@Override public Health health() { Map<String, Health> healths = circuitBreakerRegistry.getAllCircuitBreakers().stream() .filter(this::isRegisterHealthIndicator) .collect(Collectors.toMap(CircuitBreaker::getName, this::mapBackendMonitorState)); Status status ...
@Test public void testHealthStatus() { CircuitBreaker openCircuitBreaker = mock(CircuitBreaker.class); CircuitBreaker halfOpenCircuitBreaker = mock(CircuitBreaker.class); CircuitBreaker closeCircuitBreaker = mock(CircuitBreaker.class); Map<CircuitBreaker.State, CircuitBreaker> expec...
public RowExpression rewriteExpression(RowExpression expression, Predicate<VariableReferenceExpression> variableScope) { checkArgument(determinismEvaluator.isDeterministic(expression), "Only deterministic expressions may be considered for rewrite"); return rewriteExpression(expression, variableScope...
@Test public void testTriviallyRewritable() { EqualityInference.Builder builder = new EqualityInference.Builder(METADATA); RowExpression expression = builder.build() .rewriteExpression(someExpression("a1", "a2"), matchesVariables("a1", "a2")); assertEquals(expression, so...
public synchronized TableId createTable(String tableName, Schema schema) throws BigQueryResourceManagerException { return createTable(tableName, schema, System.currentTimeMillis() + 3600000); // 1h }
@Test public void testCreateTableShouldThrowErrorWhenSchemaIsNull() { assertThrows(IllegalArgumentException.class, () -> testManager.createTable(TABLE_NAME, null)); }
@Override public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { // 校验旧密码密码 validateOldPassword(id, reqVO.getOldPassword()); // 执行更新 AdminUserDO updateObj = new AdminUserDO().setId(id); updateObj.setPassword(encodePassword(reqVO.getNewPassword())); //...
@Test public void testUpdateUserPassword_success() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(o -> o.setPassword("encode:tudou")); userMapper.insert(dbUser); // 准备参数 Long userId = dbUser.getId(); UserProfileUpdatePasswordReqVO reqVO = randomPojo(UserProfileUp...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void atTest() throws Exception { DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resolve(testMethod, new Object[]{}, "@"); assertThat(result).isEqualTo("@")...
@Override public void accept(ICOSVisitor visitor) throws IOException { visitor.visitFromInt(this); }
@Override @Test void testAccept() { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); COSWriter visitor = new COSWriter(outStream); int index = 0; try { for (int i = -1000; i < 3000; i += 200) { index = i; ...
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors( ReconnaissanceReport reconnaissanceReport) { return tsunamiPlugins.entrySet().stream() .filter(entry -> isVulnDetector(entry.getKey())) .map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc...
@Test public void getVulnDetectors_whenRemoteDetectorOsFilterHasMatchingService_returnsMatchedService() { NetworkService wordPressService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtoco...
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(command, delay, unit); }
@Test public void schedule1() { underTest.schedule(callable, delay, SECONDS); verify(executorService).schedule(callable, delay, SECONDS); }
@Override public void writeInt(final int v) throws IOException { ensureAvailable(INT_SIZE_IN_BYTES); MEM.putInt(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v); pos += INT_SIZE_IN_BYTES; }
@Test public void testWriteIntV() throws Exception { int expected = 100; out.writeInt(expected); int actual = Bits.readInt(out.buffer, 0, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN); assertEquals(expected, actual); }
@Override public void subscribe(Subscriber<? super T>[] subscribers) { if (!validate(subscribers)) { return; } @SuppressWarnings("unchecked") Subscriber<? super T>[] newSubscribers = new Subscriber[subscribers.length]; for (int i = 0; i < subscribers.length; i++) { AutoDisposingSubscr...
@Test public void autoDispose_withMaybe_normal() { TestSubscriber<Integer> firstSubscriber = new TestSubscriber<>(); TestSubscriber<Integer> secondSubscriber = new TestSubscriber<>(); PublishProcessor<Integer> source = PublishProcessor.create(); CompletableSubject scope = CompletableSubject.create(); ...
public static List<PortDescription> parseCiscoIosPorts(String interfacesReply) { String parentInterface; String[] parentArray; String tempString; List<PortDescription> portDesc = Lists.newArrayList(); int interfacesCounter = interfacesCounterMethod(interfacesReply); for (...
@Test public void controllersIntfs() { InputStream streamOrig = getClass().getResourceAsStream(SHOW_INTFS); String rpcReply = new Scanner(streamOrig, "UTF-8").useDelimiter("\\Z").next(); List<PortDescription> actualIntfs = TextBlockParserCisco.parseCiscoIosPorts(rpcReply); assertEqua...
public static String read(Reader reader) throws IOException { try (StringWriter writer = new StringWriter()) { write(reader, writer); return writer.getBuffer().toString(); } }
@Test void testRead() throws Exception { assertThat(IOUtils.read(reader), equalTo(TEXT)); }
public static Duration convertFreshnessToDuration(IntervalFreshness intervalFreshness) { // validate the freshness value firstly validateIntervalFreshness(intervalFreshness); long interval = Long.parseLong(intervalFreshness.getInterval()); switch (intervalFreshness.getTimeUnit()) { ...
@Test void testConvertFreshnessToDuration() { // verify second Duration actualSecond = convertFreshnessToDuration(IntervalFreshness.ofSecond("20")); assertThat(actualSecond).isEqualTo(Duration.ofSeconds(20)); // verify minute Duration actualMinute = convertFreshnessToDuratio...
public void publishNamespace(final String releaseTitle, final String releaseComment) { NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); namespaceReleaseDTO.setReleaseTitle(releaseTitle); namespaceReleaseDTO.setReleaseComment(releaseComment); namespaceReleaseDTO.setRel...
@Test public void testPublishNamespace() { doNothing().when(apolloClient).publishNamespace(Mockito.any(), Mockito.any()); apolloClient.publishNamespace("Dr", "1.0.2"); verify(apolloClient).publishNamespace(Mockito.any(), Mockito.any()); }
public static RestSettingBuilder get(final String id) { return get(eq(checkId(id))); }
@Test public void should_throw_exception_for_get_id_with_slash() { assertThrows(IllegalArgumentException.class, () -> get("1/1").response(status(200))); }
ClassLoader connectorLoader(String connectorClassOrAlias) { String fullName = aliases.getOrDefault(connectorClassOrAlias, connectorClassOrAlias); ClassLoader classLoader = pluginClassLoader(fullName); if (classLoader == null) classLoader = this; log.debug( "Getting plugin cla...
@Test public void testEmptyConnectorLoader() { assertSame(classLoader, classLoader.connectorLoader(ARBITRARY)); }
public void retain(IndexSet indexSet, @Nullable Integer maxNumberOfIndices, RetentionExecutor.RetentionAction action, String actionName) { final Map<String, Set<String>> deflectorIndices = indexSet.getAllIndexAliases(); final int ind...
@Test public void shouldRetainOldestIndex() { underTest.retain(indexSet, 5, action, "action"); verify(action, times(1)).retain(retainedIndexName.capture(), eq(indexSet)); assertThat(retainedIndexName.getValue()).containsExactly("test_1"); verify(activityWriter, times(2)).write(any(...
public StatusRpcException asException() { return new StatusRpcException(this); }
@Test void asException() { StatusRpcException exception = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .asException(); Assertions.assertEquals(Code.NOT_FOUND, exception.getStatus().code); }
@POST @Path(KMSRESTConstants.KEYS_RESOURCE) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8) @SuppressWarnings("unchecked") public Response createKey(Map jsonKey) throws Exception { try{ LOG.trace("Entering createKey Method."); KMSWebApp.get...
@Test public void testServicePrincipalACLs() throws Exception { Configuration conf = new Configuration(); conf.set("hadoop.security.authentication", "kerberos"); File testDir = getTestDir(); conf = createBaseKMSConf(testDir, conf); conf.set("hadoop.kms.authentication.type", "kerberos"); conf.s...
public static JSONObject parseObj(String jsonStr) { return new JSONObject(jsonStr); }
@Test public void duplicateKeyFalseTest() { final String str = "{id:123, name:\"张三\", name:\"李四\"}"; final JSONObject jsonObject = JSONUtil.parseObj(str, JSONConfig.create().setCheckDuplicate(false)); assertEquals("{\"id\":123,\"name\":\"李四\"}", jsonObject.toString()); }
public Token<AMRMTokenIdentifier> launchUAM() throws YarnException, IOException { this.connectionInitiated = true; // Blocking call to RM Token<AMRMTokenIdentifier> amrmToken = initializeUnmanagedAM(this.applicationId); // Creates the UAM connection createUAMProxy(amrmToken); return amrm...
@Test public void testSeparateThreadWithoutBlockServiceStop() throws Exception { ApplicationAttemptId attemptId1 = ApplicationAttemptId.newInstance(ApplicationId.newInstance(Time.now(), 1), 1); Token<AMRMTokenIdentifier> token1 = uamPool.launchUAM("SC-1", this.conf, attemptId1.getApplicationId...
public static <T> void forEach(Iterable<T> iterable, Procedure<? super T> procedure) { FJIterate.forEach(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
@Test public void testForEachUsingMap() { //Test the default batch size calculations IntegerSum sum1 = new IntegerSum(0); MutableMap<String, Integer> map1 = Interval.fromTo(1, 100).toMap(Functions.getToString(), Functions.getIntegerPassThru()); FJIterate.forEach(map1, new SumProc...
public static PortabilityJob.Builder builder() { Instant now = Instant.now(); // TODO: Fix so we don't need fully qualified name here. This is to get IntelliJ to recognize // the class name due to a conflict in package names for our generated code, but the conflict // doesn't cause any actual problems w...
@Test public void verifySerializeDeserializeWithAlbum() throws IOException { ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); Instant date = Instant.now(); JobAuthorization jobAuthorization = JobAuthorization.builder() .setState(JobAuthorization.State.INITIAL) ...
@Override public Optional<FunctionDefinition> getFunctionDefinition(String name) { if (BUILT_IN_FUNC_BLACKLIST.contains(name)) { return Optional.empty(); } FunctionDefinitionFactory.Context context = () -> classLoader; // We override some Hive's function by native implem...
@Test public void testNonExistFunction() { assertThat(new HiveModule().getFunctionDefinition("nonexist")).isNotPresent(); }
@Override public void pickSuggestionManually( int index, CharSequence suggestion, boolean withAutoSpaceEnabled) { if (getCurrentComposedWord().isAtTagsSearchState()) { if (index == 0) { // this is a special case for tags-searcher // since we append a magnifying glass to the suggestions...
@Test public void testPickingTypedTagDoesNotTryToAddToAutoDictionary() throws Exception { verifyNoSuggestionsInteractions(); mAnySoftKeyboardUnderTest.simulateTextTyping(":face"); Mockito.reset(mAnySoftKeyboardUnderTest.getSuggest()); mAnySoftKeyboardUnderTest.pickSuggestionManually(0, ":face"); ...
@Override public ComputeNode getWorkerById(long workerId) { return availableID2ComputeNode.get(workerId); }
@Test public void testCaptureAvailableWorkers() { long deadBEId = 1L; long deadCNId = 11L; long inBlacklistBEId = 3L; long inBlacklistCNId = 13L; HostBlacklist blockList = SimpleScheduler.getHostBlacklist(); blockList.add(inBlacklistBEId); blockList.add(inBl...
@Override public void run() { try { backgroundJobServer.getJobSteward().notifyThreadOccupied(); MDCMapper.loadMDCContextFromJob(job); performJob(); } catch (Exception e) { if (isJobDeletedWhileProcessing(e)) { // nothing to do anymore a...
@Test void allStateChangesArePassingViaTheApplyStateFilterOnFailure() { Job job = anEnqueuedJob().build(); when(backgroundJobServer.getBackgroundJobRunner(job)).thenReturn(null); BackgroundJobPerformer backgroundJobPerformer = new BackgroundJobPerformer(backgroundJobServer, job); f...
static <T, W extends BoundedWindow> AssignWindowsRunner<T, W> create( WindowFn<? super T, W> windowFn) { // Safe contravariant cast WindowFn<T, W> typedWindowFn = (WindowFn<T, W>) windowFn; return new AssignWindowsRunner<>(typedWindowFn); }
@Test public void factoryCreatesFromJavaWindowFn() throws Exception { SdkComponents components = SdkComponents.create(); components.registerEnvironment(Environments.createDockerEnvironment("java")); PTransform windowPTransform = PTransform.newBuilder() .putInputs("in", "input") ...
public boolean compatibleVersion(String acceptableVersionRange, String actualVersion) { V pluginVersion = parseVersion(actualVersion); // Treat a single version "1.4" as a left bound, equivalent to "[1.4,)" if (acceptableVersionRange.matches(VERSION_REGEX)) { return ge(pluginVersion, parseVersion(acc...
@Test public void testRange_leftOpen() { Assert.assertFalse(checker.compatibleVersion("(2.3,4.3]", "1.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "1.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,)", "1.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,]", "1.0"));...
public boolean isFreshInstallation() { return isFreshInstallation.get(); }
@Test public void testIsFreshInstallation() { mongoDBPreflightCheck.runCheck(); assertThat(mongoDBPreflightCheck.isFreshInstallation()).isTrue(); }
public Set<String> getLangs() { return langs; }
@Test public void testThreadJoinInLoadingLangs() throws Exception { assumeTrue(canRun()); //make sure that the stream is fully read and //we're getting the same answers on several iterations Set<String> langs = getLangs(); assumeTrue(langs.size() > 0); for (int i = 0;...
public boolean shouldSample(String service, int sample, int duration) { SamplingPolicy samplingPolicy = this.samplingPolicySettings.get().get(service); if (samplingPolicy == null) { return shouldSampleByDefault(sample, duration); } return shouldSampleService(samplingPolicy, s...
@Test @Timeout(20) public void testDefaultSampleRateDynamicUpdate() throws InterruptedException { ConfigWatcherRegister register = new DefaultSampleRateMockConfigWatcherRegister(3); TraceSamplingPolicyWatcher watcher = new TraceSamplingPolicyWatcher(moduleConfig, provider); register.reg...