focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Set<Pod> pods() { return ImmutableSet.copyOf(kubevirtPodStore.pods()); }
@Test public void testGetPods() { createBasicPods(); assertEquals("Number of pods did not match", 1, target.pods().size()); }
public ImmutableList<GlobalSetting> parse(final InputStream is) { return Jsons.toObjects(is, GlobalSetting.class); }
@Test public void should_parse_setting_file_with_file_root() { InputStream stream = getResourceAsStream("settings/fileroot-settings.json"); ImmutableList<GlobalSetting> globalSettings = parser.parse(stream); assertThat(globalSettings.get(0).includes().get(0), is(join("src", "test", "resourc...
@Override public void applyToAllPartitions( TwoOutputApplyPartitionFunction<OUT1, OUT2> applyPartitionFunction) throws Exception { if (isKeyed) { for (Object key : keySet) { partitionedContext .getStateManager() .execute...
@Test void testApplyToAllPartitions() throws Exception { AtomicInteger counter = new AtomicInteger(0); List<Integer> collectedFromFirstOutput = new ArrayList<>(); List<Long> collectedFromSecondOutput = new ArrayList<>(); TestingTimestampCollector<Integer> firstCollector = ...
@SuppressWarnings("unchecked") @Override public OUT extract(Object in) { return (OUT) Array.get(in, fieldId); }
@Test void testIntArray() { for (int i = 0; i < this.testIntArray.length; i++) { assertThat(new FieldFromArray<Integer>(i).extract(testIntArray)) .isEqualTo(new Integer(testIntArray[i])); } }
public boolean verifySignedPip(ASN1Sequence signedPip) throws BsnkException { ASN1Sequence signedPipContent = (ASN1Sequence) signedPip.getObjectAt(1); ASN1Sequence pipSignatureSequence = (ASN1Sequence) signedPip.getObjectAt(2); ASN1Sequence pipSignature = (ASN1Sequence) pipSignatureSequence.getO...
@Test public void verifySignedPipFailTest() throws IOException, BsnkException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException { String invalidUBase64 = "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"; ...
@SuppressWarnings("deprecation") public boolean setSocketOpt(int option, Object optval) { final ValueReference<Boolean> result = new ValueReference<>(false); switch (option) { case ZMQ.ZMQ_SNDHWM: sendHwm = (Integer) optval; if (sendHwm < 0) { thro...
@Test(expected = IllegalArgumentException.class) public void testHeartbeatTimeoutUnderflow() { options.setSocketOpt(ZMQ.ZMQ_HEARTBEAT_TIMEOUT, -1); }
@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 periodicWatermarksBatchMode() throws Exception { OneInputStreamOperatorTestHarness<Long, Long> testHarness = createBatchHarness( WatermarkStrategy.forGenerator((ctx) -> new PeriodicWatermarkGenerator()) .withTimestampAssigner...
public static String toIpString(InetSocketAddress address) { if (address == null) { return null; } else { InetAddress inetAddress = address.getAddress(); return inetAddress == null ? address.getHostName() : inetAddress.getHostAddress(); } }
@Test public void toIpString() throws Exception { }
@Override public synchronized ManagerSpec getManagerSpec() { Set<Long> rootGroupIds = new HashSet<>(); Map<Long, ResourceGroupSpec> resourceGroupSpecMap = new HashMap<>(); Map<Long, ResourceGroupIdTemplate> resourceGroupIdTemplateMap = new HashMap<>(); Map<Long, ResourceGroupSpec...
@Test public void testSubgroups() { H2DaoProvider daoProvider = setup("test_dup_roots"); H2ResourceGroupsDao dao = daoProvider.get(); dao.createResourceGroupsGlobalPropertiesTable(); dao.createResourceGroupsTable(); dao.createSelectorsTable(); dao.insertResourceGr...
@VisibleForTesting public BlockPlacementPolicy getBlockPlacementPolicy() { return placementPolicies.getPolicy(CONTIGUOUS); }
@Test public void testUseDelHint() { DatanodeStorageInfo delHint = new DatanodeStorageInfo( DFSTestUtil.getLocalDatanodeDescriptor(), new DatanodeStorage("id")); List<DatanodeStorageInfo> moreThan1Racks = Arrays.asList(delHint); List<StorageType> excessTypes = new ArrayList<>(); BlockPlacement...
@Override public byte[] serialize(final String topic, final TimestampedKeyAndJoinSide<K> data) { final byte boolByte = (byte) (data.isLeftSide() ? 1 : 0); final byte[] keyBytes = keySerializer.serialize(topic, data.getKey()); final byte[] timestampBytes = timestampSerializer.serialize(topic,...
@Test public void shouldSerializeKeyWithJoinSideAsTrue() { final String value = "some-string"; final TimestampedKeyAndJoinSide<String> timestampedKeyAndJoinSide = TimestampedKeyAndJoinSide.makeLeft(value, 10); final byte[] serialized = STRING_SERDE.serializer().serialize(TOPIC,...
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { String fullName = aliases.getOrDefault(name, name); PluginClassLoader pluginLoader = pluginClassLoader(fullName); if (pluginLoader != null) { log.trace("Retrieving loaded class '{...
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void testEmptyLoadClass() throws ClassNotFoundException { when(parent.loadClass(ARBITRARY, false)).thenReturn((Class) ARBITRARY_CLASS); assertSame(ARBITRARY_CLASS, classLoader.loadClass(ARBITRARY, false)); }
public void isNotIn(@Nullable Iterable<?> iterable) { checkNotNull(iterable); if (Iterables.contains(iterable, actual)) { failWithActual("expected not to be any of", iterable); } }
@Test public void isNotInEmpty() { assertThat("b").isNotIn(ImmutableList.<String>of()); }
@PutMapping("/{id}") public ShenyuAdminResult updateSelector(@PathVariable("id") @Valid @Existed(provider = SelectorMapper.class, message = "selector is not existed") final String id, @Valid @RequestBody final SelectorDTO select...
@Test public void updateSelector() throws Exception { SelectorDTO selectorDTO = SelectorDTO.builder() .id("123") .name("test123") .continued(true) .type(1) .loged(true) .enabled(true) .matchRestfu...
String buildCustomMessage(EventNotificationContext ctx, SlackEventNotificationConfig config, String template) throws PermanentEventNotificationException { final List<MessageSummary> backlog = getMessageBacklog(ctx, config); Map<String, Object> model = getCustomMessageModel(ctx, config.type(), backlog, c...
@Test public void buildCustomMessage() throws PermanentEventNotificationException { String s = slackEventNotification.buildCustomMessage(eventNotificationContext, slackEventNotificationConfig, "${thisDoesnotExist}"); assertThat(s).isEmpty(); String expectedCustomMessage = slackEventNotificat...
@Override public List<String> getServerList() { return serverList.isEmpty() ? serversFromEndpoint : serverList; }
@Test void testConstructEndpointContextPathPriority() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, "ccc"...
public boolean isSubscribed(String groupName, String serviceName) { String subId = NamingUtils.getGroupedName(serviceName, groupName); return selectorManager.isSubscribed(subId); }
@Test void testIsSubscribed() { List<String> clusters = Collections.singletonList(CLUSTER_STR_CASE); EventListener listener = Mockito.mock(EventListener.class); NamingSelector selector = NamingSelectorFactory.newClusterSelector(clusters); assertFalse(instancesChangeNotifier.isSubscri...
public static WindowBytesStoreSupplier persistentTimestampedWindowStore(final String name, final Duration retentionPeriod, final Duration windowSize, ...
@Test public void shouldThrowIfIPersistentTimestampedWindowStoreRetentionPeriodIsNegative() { final Exception e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentTimestampedWindowStore("anyName", ofMillis(-1L), ZERO, false)); assertEquals("retentionPeriod cannot be negative", e.g...
public static <K, V> Read<K, V> read() { return new AutoValue_KafkaIO_Read.Builder<K, V>() .setTopics(new ArrayList<>()) .setTopicPartitions(new ArrayList<>()) .setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN) .setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES) ...
@Test public void testUnboundedSourceCheckpointMarkWithEmptyPartitions() throws Exception { // Similar to testUnboundedSourceCheckpointMark(), but verifies that source resumes // properly from empty partitions, without missing messages added since checkpoint. // Initialize consumer with fewer elements th...
public static RepositoryMetadataStore getInstance() { return repositoryMetadataStore; }
@Test public void shouldPopulateDataCorrectly() throws Exception { PackageConfigurations repositoryConfigurationPut = new PackageConfigurations(); RepositoryMetadataStore.getInstance().addMetadataFor("plugin-id", repositoryConfigurationPut); assertThat(RepositoryMetadataStore.getInstance()....
@Override public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) { checkForDynamicType(typeDescriptor); return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType()); }
@Test public void testPrimitiveSchema() { Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(Primitive.class)); assertEquals(PRIMITIVE_SCHEMA, schema); }
public static boolean isBlank(String value) { return value == null || value.isEmpty(); }
@Test void isBlankInputNotNullOutputFalse() { // Arrange final String value = "AAAAAAAA"; // Act final boolean retval = Util.isBlank(value); // Assert result assertThat(retval).isEqualTo(false); }
boolean contains(Point p) { return p.coordinateX >= this.coordinateX - this.width / 2 && p.coordinateX <= this.coordinateX + this.width / 2 && p.coordinateY >= this.coordinateY - this.height / 2 && p.coordinateY <= this.coordinateY + this.height / 2; }
@Test void containsTest() { var r = new Rect(10, 10, 20, 20); var b1 = new Bubble(2, 2, 1, 1); var b2 = new Bubble(30, 30, 2, 1); //r contains b1 and not b2 assertTrue(r.contains(b1)); assertFalse(r.contains(b2)); }
@Override public void close() { finished(); if (logAtInfo) { log.info("{}", this); } else { if (log.isDebugEnabled()) { log.debug("{}", this); } } }
@Test(expected = NullPointerException.class) public void testDurationInfoCreationWithNullMsg() { DurationInfo info = new DurationInfo(log, null); info.close(); }
public CompletableFuture<Map<TopicIdPartition, Acknowledgements>> commitSync( final Map<TopicIdPartition, Acknowledgements> acknowledgementsMap, final long deadlineMs) { final AtomicInteger resultCount = new AtomicInteger(); final CompletableFuture<Map<TopicIdPartition, Acknowled...
@Test public void testCommitSync() { buildRequestManager(); assignFromSubscribed(Collections.singleton(tp0)); // normal fetch assertEquals(1, sendFetches()); assertFalse(shareConsumeRequestManager.hasCompletedFetches()); client.prepareResponse(fullFetchResponse(tip...
public FEELFnResult<Boolean> invoke(@ParameterName( "range" ) Range range, @ParameterName( "point" ) Comparable point) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { ret...
@Test void invokeParamsCantBeCompared() { FunctionTestUtil.assertResultError( includesFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, 1, 2, Range.RangeBoundary.CLOSED ) ), InvalidP...
public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize); int actualSize = size(checkNotNull(actual)); check("size()").that(actualSize).isEqualTo(expectedSize); }
@Test @SuppressWarnings({"TruthIterableIsEmpty", "IsEmptyTruth"}) public void hasSizeZero() { assertThat(ImmutableList.of()).hasSize(0); }
@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); }
@SuppressWarnings("deprecation") @Test public void shouldProcessWithOldProcessorAndState() { final Consumed<String, String> consumed = Consumed.with(Serdes.String(), Serdes.String()); final StreamsBuilder builder = new StreamsBuilder(); final String input = "input"; builder.ad...
public static Read read() { return new AutoValue_MongoDbIO_Read.Builder() .setMaxConnectionIdleTime(60000) .setNumSplits(0) .setBucketAuto(false) .setSslEnabled(false) .setIgnoreSSLCertificate(false) .setSslInvalidHostNameAllowed(false) .setQueryFn(FindQuery.c...
@Test public void testReadWithFilter() { PCollection<Document> output = pipeline.apply( MongoDbIO.read() .withUri("mongodb://localhost:" + port) .withDatabase(DATABASE_NAME) .withCollection(COLLECTION_NAME) .withQueryFn(FindQuery....
public final void containsEntry(@Nullable Object key, @Nullable Object value) { Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value); checkNotNull(actual); if (!actual.entrySet().contains(entry)) { List<@Nullable Object> keyList = singletonList(key); List<@Nullable Ob...
@Test public void containsExactly_bothExactAndToStringKeyMatches_showsExactKeyMatch() { ImmutableMap<Number, String> actual = ImmutableMap.of(1, "actual int", 1L, "actual long"); expectFailureWhenTestingThat(actual).containsEntry(1L, "expected long"); // should show the exact key match, 1="actual int", no...
@ScalarOperator(GREATER_THAN) @SqlType(StandardTypes.BOOLEAN) public static boolean greaterThan(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right) { return left > right; }
@Test public void testGreaterThan() { assertFunction("TINYINT'37' > TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'37' > TINYINT'17'", BOOLEAN, true); assertFunction("TINYINT'17' > TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'17' > TINYINT'17'", BOOLEAN, false);...
public static ProxyBackendHandler newInstance(final DatabaseType databaseType, final String sql, final SQLStatement sqlStatement, final ConnectionSession connectionSession, final HintValueContext hintValueContext) throws SQLException { if (sqlStatement instanceo...
@Test void assertNewInstanceWithShow() throws SQLException { String sql = "SHOW VARIABLES LIKE '%x%'"; SQLStatement sqlStatement = ProxySQLComQueryParser.parse(sql, databaseType, connectionSession); ProxyBackendHandler actual = ProxyBackendHandlerFactory.newInstance(databaseType, sql, sqlSta...
public List<BlameLine> blame(Git git, String filename) { BlameResult blameResult; try { blameResult = git.blame() // Equivalent to -w command line option .setTextComparator(RawTextComparator.WS_IGNORE_ALL) .setFilePath(filename).call(); } catch (Exception e) { throw new I...
@Test public void symlink_doesnt_fail() throws IOException { assumeTrue(!System2.INSTANCE.isOsWindows()); String relativePath2 = "src/main/java/org/dummy/Dummy2.java"; // Create symlink Files.createSymbolicLink(baseDir.resolve(relativePath2), baseDir.resolve(DUMMY_JAVA)); try (Git git = loadRepo...
@Override @Transactional public boolean updateAfterApproval(Long userId, Integer userType, String clientId, Map<String, Boolean> requestedScopes) { // 如果 requestedScopes 为空,说明没有要求,则返回 true 通过 if (CollUtil.isEmpty(requestedScopes)) { return true; } // 更新批准的信息 ...
@Test public void testUpdateAfterApproval_none() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); String clientId = randomString(); // 调用 boolean success = oauth2ApproveService.updateAfterApproval(userId, userTyp...
public long headSlowTimeMills(BlockingQueue<Runnable> q) { long slowTimeMills = 0; final Runnable peek = q.peek(); if (peek != null) { RequestTask rt = BrokerFastFailure.castRunnable(peek); slowTimeMills = rt == null ? 0 : this.messageStore.now() - rt.getCreateTimestamp()...
@Test public void testHeadSlowTimeMills() throws Exception { BrokerController brokerController = new BrokerController(brokerConfig, nettyServerConfig, new NettyClientConfig(), messageStoreConfig); brokerController.initialize(); BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); ...
@Udf public String trim( @UdfParameter( description = "The string to trim") final String input) { if (input == null) { return null; } return input.trim(); }
@Test public void shouldReturnNullForNullInput() { final String result = udf.trim(null); assertThat(result, is(nullValue())); }
public void replayLoadDynamicPlugin(PluginInfo info) throws IOException, UserException { DynamicPluginLoader pluginLoader = new DynamicPluginLoader(Config.plugin_dir, info); try { // should add to "plugins" first before loading. PluginLoader checkLoader = plugins[info.getTypeId()...
@Test public void testLoadPluginFail() { try { PluginMgr pluginMgr = GlobalStateMgr.getCurrentState().getPluginMgr(); PluginInfo info = new PluginInfo(); info.name = "plugin-name"; info.type = PluginType.AUDIT; info.description = "plugin descripti...
public static ImmutableSet<HttpUrl> allSubPaths(String url) { return allSubPaths(HttpUrl.parse(url)); }
@Test public void allSubPaths_whenMultipleSubPathsNoTrailingSlash_returnsExpectedUrl() { assertThat(allSubPaths("http://localhost/a/b/c")) .containsExactly( HttpUrl.parse("http://localhost/"), HttpUrl.parse("http://localhost/a/"), HttpUrl.parse("http://localhost/a/b/"),...
public Object execute(ProceedingJoinPoint proceedingJoinPoint, Method method, String fallbackMethodValue, CheckedSupplier<Object> primaryFunction) throws Throwable { String fallbackMethodName = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), fallbackMethodValue); FallbackMethod fallbackMeth...
@Test public void testPrimaryMethodExecutionWithFallbackWithIncorrectSignature() throws Throwable { Method method = this.getClass().getMethod("getName", String.class); final CheckedSupplier<Object> primaryFunction = () -> getName("Name"); final String fallbackMethodValue = "getNameInvalidFal...
@Override public void handle(ContainersLauncherEvent event) { // TODO: ContainersLauncher launches containers one by one!! Container container = event.getContainer(); ContainerId containerId = container.getContainerId(); switch (event.getType()) { case LAUNCH_CONTAINER: Application app =...
@Test public void testResumeContainerEvent() throws IllegalArgumentException, IllegalAccessException, IOException { spy.running.clear(); spy.running.put(containerId, containerLaunch); when(event.getType()) .thenReturn(ContainersLauncherEventType.RESUME_CONTAINER); doNothing().when(contai...
@Override public Runner get() { if (runner == null) { runner = createRunner(); } return runner; }
@Test void should_return_the_same_runner_on_subsequent_calls() { assertThat(runnerSupplier.get(), is(equalTo(runnerSupplier.get()))); }
@Override public <E extends Extension> ExtensionStore convertTo(E extension) { var gvk = extension.groupVersionKind(); var scheme = schemeManager.get(gvk); try { var convertedExtension = Optional.of(extension) .map(item -> scheme.type().isAssignableFrom(item.getC...
@Test void shouldThrowSchemaViolationExceptionWhenNameNotSet() { var fake = new FakeExtension(); Metadata metadata = new Metadata(); fake.setMetadata(metadata); fake.setApiVersion("fake.halo.run/v1alpha1"); fake.setKind("Fake"); var error = assertThrows(SchemaViolatio...
public boolean isEnabled() { return enabled; }
@Test public void testJetIsDisabledByDefault() { assertFalse(new JetConfig().isEnabled()); assertFalse(new Config().getJetConfig().isEnabled()); }
public void changeFieldType(final CustomFieldMapping customMapping, final Set<String> indexSetsIds, final boolean rotateImmediately) { checkFieldTypeCanBeChanged(customMapping.fieldName()); checkType(customMapping); checkAllIndicesS...
@Test void testDoesNotCycleIndexSetWhenMappingAlreadyExisted() { doReturn(Optional.of(existingIndexSet)).when(indexSetService).get("existing_index_set"); toTest.changeFieldType(existingCustomFieldMapping, new LinkedHashSet<>(List.of("existing_index_set", "wrong_index_set")), ...
@Override public void execute(Context context) { try (CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse()) { while (issues.hasNext()) { DefaultIssue issue = issues.next(); if (shouldUpdateIndexForIssue(issue)) { changedIssuesRepository.addIssueKey(issue.key()); ...
@Test public void execute_whenIssueIsNew_shouldLoadIssue() { protoIssueCache.newAppender() .append(newDefaultIssue().setNew(true)) .close(); underTest.execute(mock(ComputationStep.Context.class)); verify(changedIssuesRepository).addIssueKey("issueKey1"); }
public static boolean removeDisabledPartitions(InstanceConfig instanceConfig) { ZNRecord record = instanceConfig.getRecord(); String disabledPartitionsKey = InstanceConfig.InstanceConfigProperty.HELIX_DISABLED_PARTITION.name(); boolean listUpdated = record.getListFields().remove(disabledPartitionsKey) != nu...
@Test public void testRemoveDisabledPartitions() { String instanceId = "Server_myInstance"; InstanceConfig instanceConfig = new InstanceConfig(instanceId); assertTrue(instanceConfig.getDisabledPartitionsMap().isEmpty()); assertFalse(HelixHelper.removeDisabledPartitions(instanceConfig)); instanceC...
@Override public Long createNotifyMessage(Long userId, Integer userType, NotifyTemplateDO template, String templateContent, Map<String, Object> templateParams) { NotifyMessageDO message = new NotifyMessageDO().setUserId(userId).setUserType(userType) .setTe...
@Test public void testCreateNotifyMessage_success() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class); String templateContent = randomString(); Map<Str...
@Override public void decode() throws Exception { if (!hasDecoded && channel != null && inputStream != null) { try { decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "...
@Test void test() throws Exception { // Simulate the data called by the client(The called data is stored in invocation and written to the buffer) URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); RpcInvocation inv = new RpcInvocati...
public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime) { ScalingQueue<Runnable> queue = new ScalingQueue<>(); ThreadPoolExecutor executor = new ScalingThreadPoolExecutor(min, max, keepAliveTime, TimeUnit.MILLISECONDS, queue); executor.setRejectedExecutionHandler(new ForceQu...
@Test public void testCreateThreadPerRunnable() { ThreadPoolExecutor executorService = (ThreadPoolExecutor) ScalingThreadPoolExecutor.newScalingThreadPool(0, 5, 500); assertEquals(executorService.getLargestPoolSize(), 0); for (int i = 0; i < 5; i++) { executorService.submit(getSleepingRunnable()); ...
@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_json() { InternalSerializationService ss = new DefaultSerializationServiceBuilder().build(); Metadata metadata = SampleMetadataResolver.resolve(ss, new HazelcastJsonValue("{}"), key); assertThat(metadata).isNull(); metadata = SampleMetadataResolver.resolve(ss...
public ClusterStateBundle.FeedBlock inferContentClusterFeedBlockOrNull(ContentCluster cluster) { if (!feedBlockEnabled) { return null; } var nodeInfos = cluster.getNodeInfos(); var exhaustions = enumerateNodeResourceExhaustionsAcrossAllNodes(nodeInfos); if (exhaustion...
@Test void retain_node_feed_block_status_when_within_hysteresis_window_limit_crossed_edge_case() { var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.51))); var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public NodeInfo get() { return getNodeInfo(); }
@Test public void testSingleNodesXML() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("node") .path("info/").accept(MediaType.APPLICATION_XML) .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_XML+ "; " + Je...
public static SeaTunnelDataType<?> mapping(String tdengineType) { switch (tdengineType) { case TDENGINE_BOOL: case TDENGINE_BIT: return BasicType.BOOLEAN_TYPE; case TDENGINE_TINYINT: case TDENGINE_TINYINT_UNSIGNED: case TDENGINE_SMALLIN...
@Test void mapping() { SeaTunnelDataType<?> type = TDengineTypeMapper.mapping("BOOL"); Assertions.assertEquals(BasicType.BOOLEAN_TYPE, type); type = TDengineTypeMapper.mapping("CHAR"); Assertions.assertEquals(BasicType.STRING_TYPE, type); }
public static PathMatcherPredicate matches(final List<String> patterns) { return new PathMatcherPredicate(null, patterns); }
@Test void shouldMatchGivenSimpleExpressionAndBasePath() { // Given List<Path> paths = Stream.of("/base/test.txt", "/base/sub/dir/test.txt").map(Path::of).toList(); PathMatcherPredicate predicate = PathMatcherPredicate.matches(Path.of("/base"), List.of("test.txt")); // When L...
@Override public DdlCommand create( final String sqlExpression, final DdlStatement ddlStatement, final SessionConfig config ) { return FACTORIES .getOrDefault(ddlStatement.getClass(), (statement, cf, ci) -> { throw new KsqlException( "Unable to find ddl command ...
@Test public void shouldCreateCommandForCreateSourceTable() { // Given: final CreateTable statement = new CreateTable(SOME_NAME, TableElements.of( tableElement("COL1", new Type(SqlTypes.BIGINT)), tableElement("COL2", new Type(SqlTypes.STRING))), false, true, withPropert...
@PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updatePort(@PathParam("id") String id, InputStream input) throws IOException { log.trace(String.format(MESSAGE, "UPDATE " + id)); String inputStr = IOUtils.toString(input, REST...
@Test public void testUpdatePortWithNonexistId() { expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes(); replay(mockOpenstackHaService); mockOpenstackNetworkAdminService.updatePort(anyObject()); expectLastCall().andThrow(new IllegalArgumentException()); repla...
public boolean isService(Object bean, String beanName) { for (RemotingParser remotingParser : allRemotingParsers) { if (remotingParser.isService(bean, beanName)) { return true; } } return false; }
@Test public void testIsServiceFromObject() { SimpleRemoteBean remoteBean = new SimpleRemoteBean(); assertTrue(remotingParser.isService(remoteBean, remoteBean.getClass().getName())); }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertInt() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.INT_TYPE).build(); BasicTypeDefine typeDefine = SqlServerTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Asserti...
public static Bar replaceBarIfChanged(BarSeries barSeries, Bar newBar) { List<Bar> bars = barSeries.getBarData(); if (bars == null || bars.isEmpty()) return null; for (int i = 0; i < bars.size(); i++) { Bar bar = bars.get(i); boolean isSameBar = bar.getBeginTi...
@Test public void replaceBarIfChangedTest() { final List<Bar> bars = new ArrayList<>(); time = ZonedDateTime.of(2019, 6, 1, 1, 1, 0, 0, ZoneId.systemDefault()); final Bar bar0 = new MockBar(time, 1d, 2d, 3d, 4d, 5d, 0d, 7, numFunction); final Bar bar1 = new MockBar(time.plusDays(1)...
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldRaiseExceptionIfKeyDoesNotExistEditablePropertiesList() { configuredStatement = configuredStatement("ALTER SYSTEM 'ksql.streams.upgrade.from'='TEST';" , alterSystemProperty); when(alterSystemProperty.getPropertyName()).thenReturn("ksql.streams.upgrade.from"); when(alterSystemProper...
public static Request.Builder buildRequestBuilder(final String url, final Map<String, ?> form, final HTTPMethod method) { switch (method) { case GET: return new Request.Builder() .url(buildHttpUrl(url, form)) .get(); case HE...
@Test public void buildRequestBuilderForPOSTTest() { Request.Builder builder = HttpUtils.buildRequestBuilder(TEST_URL, formMap, HttpUtils.HTTPMethod.POST); Assert.assertNotNull(builder); Assert.assertNotNull(builder.build().body()); Assert.assertEquals(builder.build().method(), HttpU...
@Override public Num calculate(BarSeries series, Position position) { Num average = averageCriterion.calculate(series, position); return standardDeviationCriterion.calculate(series, position).dividedBy(average); }
@Test public void calculateStandardDeviationPnL() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series, series.one()), Trade.sellAt(2, series, series.one()), Trade.buyAt(3, seri...
public static void error(final Logger logger, final String format, final Supplier<Object> supplier) { if (logger.isErrorEnabled()) { logger.error(format, supplier.get()); } }
@Test public void testNeverError() { when(logger.isErrorEnabled()).thenReturn(false); LogUtils.error(logger, supplier); verify(supplier, never()).get(); }
public static HollowIncrementalProducer.Builder withProducer(HollowProducer hollowProducer) { Builder builder = new Builder(); return builder.withProducer(hollowProducer); }
@Test(expected = IllegalArgumentException.class) public void failsWithNoProducer() { //No Hollow Producer HollowIncrementalProducer.withProducer(null) .build(); }
@Override @NotNull public BTreeMutable getMutableCopy() { final BTreeMutable result = new BTreeMutable(this); result.addExpiredLoggable(rootLoggable); return result; }
@Test public void testPutRightSortDuplicates() { tm = new BTreeEmpty(log, createTestSplittingPolicy(), true, 1).getMutableCopy(); List<INode> expected = new ArrayList<>(); expected.add(kv("1", "1")); expected.add(kv("2", "2")); expected.add(kv("3", "3")); expected.ad...
@Override public boolean imbalanceDetected(LoadImbalance imbalance) { Set<? extends MigratablePipeline> candidates = imbalance.getPipelinesOwnedBy(imbalance.srcOwner); //only attempts to migrate if at least 1 pipeline exists return !candidates.isEmpty(); }
@Test public void imbalanceDetected_shouldReturnTrueWhenPipelineExist() { MigratablePipeline pipeline = mock(MigratablePipeline.class); ownerPipelines.put(imbalance.srcOwner, Set.of(pipeline)); boolean imbalanceDetected = strategy.imbalanceDetected(imbalance); assertTrue(imbalanceDe...
public static String getHostFromPrincipal(String principalName) { return new HadoopKerberosName(principalName).getHostName(); }
@Test public void testGetHostFromPrincipal() { assertEquals("host", SecurityUtil.getHostFromPrincipal("service/host@realm")); assertEquals(null, SecurityUtil.getHostFromPrincipal("service@realm")); }
@Override public void validateInputFilePatternSupported(String filepattern) { getGcsPath(filepattern); verifyPath(filepattern); verifyPathIsAccessible(filepattern, "Could not find file %s"); }
@Test public void testFilePatternMissingBucket() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( "Missing object or bucket in path: 'gs://input/', " + "did you mean: 'gs://some-bucket/input'?"); validator.validateInputFilePatternSupported("g...
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getData(); switch (metric.getType().getValueType()) { case ...
@Test public void toMeasure_returns_no_QualityGateStatus_if_dto_has_no_alertStatus_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); }
public static Metric metric(String name) { return MetricsImpl.metric(name, Unit.COUNT); }
@Test public void availableDuringJobExecution() { int generatedItems = 1000; pipeline.readFrom(TestSources.itemStream(1_000)) .withIngestionTimestamps() .filter(l -> l.sequence() < generatedItems) .map(t -> { Metrics.metric("total"...
@Override public Processor createPreProcessor(Exchange exchange, DynamicAwareEntry entry) { Processor preProcessor = null; if (DynamicRouterControlConstants.SHOULD_OPTIMIZE.test(entry.getUri())) { preProcessor = queryParamsHeadersProcessor.apply(entry); } return preProces...
@Test void createPreProcessor() throws Exception { Mockito.when(exchange.getMessage()).thenReturn(message); Mockito.doNothing().when(message).setHeader(CONTROL_ACTION_HEADER, "subscribe"); Mockito.doNothing().when(message).setHeader(CONTROL_SUBSCRIPTION_ID, "testSub1"); String origin...
@Override public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets, ListOffsetsOptions options) { AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future = ListOffsetsHandler.newFuture(topicParti...
@Test public void testListOffsetsMaxTimestampUnsupportedSingleOffsetSpec() { Node node = new Node(0, "localhost", 8120); List<Node> nodes = Collections.singletonList(node); final Cluster cluster = new Cluster( "mockClusterId", nodes, Collections.singleton(...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldEvaluateTypeForStructExpression() { // Given: final LogicalSchema schema = LogicalSchema.builder() .keyColumn(SystemColumns.ROWKEY_NAME, SqlTypes.STRING) .valueColumn(COL0, SqlTypes.array(SqlTypes.INTEGER)) .build(); expressionTypeManager = new ExpressionTy...
@Override public void createApiErrorLog(ApiErrorLogCreateReqDTO createDTO) { ApiErrorLogDO apiErrorLog = BeanUtils.toBean(createDTO, ApiErrorLogDO.class) .setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); apiErrorLog.setRequestParams(StrUtil.maxLength(apiErrorLog.getRe...
@Test public void testCreateApiErrorLog() { // 准备参数 ApiErrorLogCreateReqDTO createDTO = randomPojo(ApiErrorLogCreateReqDTO.class); // 调用 apiErrorLogService.createApiErrorLog(createDTO); // 断言 ApiErrorLogDO apiErrorLogDO = apiErrorLogMapper.selectOne(null); as...
@Udf public Map<String, String> splitToMap( @UdfParameter( description = "Separator string and values to join") final String input, @UdfParameter( description = "Separator string and values to join") final String entryDelimiter, @UdfParameter( description = "Separator s...
@Test public void shouldDropEmptyEntriesFromSplit() { Map<String, String> result = udf.splitToMap("/foo:=apple//bar:=cherry/", "/", ":="); assertThat(result, hasEntry("foo", "apple")); assertThat(result, hasEntry("bar", "cherry")); assertThat(result.size(), equalTo(2)); }
public static ProgressLogger create(Class clazz, AtomicLong counter) { String threadName = String.format("ProgressLogger[%s]", clazz.getSimpleName()); Logger logger = LoggerFactory.getLogger(clazz); return new ProgressLogger(threadName, counter, logger); }
@Test public void create() { ProgressLogger progress = ProgressLogger.create(getClass(), new AtomicLong()); // default values assertThat(progress.getPeriodMs()).isEqualTo(60000L); assertThat(progress.getPluralLabel()).isEqualTo("rows"); // override values progress.setPeriodMs(10L); progr...
@Override public KeyValueIterator<Windowed<K>, V> all() { final NextIteratorFunction<Windowed<K>, V, ReadOnlyWindowStore<K, V>> nextIteratorFunction = ReadOnlyWindowStore::all; return new DelegatingPeekingKeyValueIterator<>( storeName, new CompositeKeyValueIterato...
@Test public void shouldGetAllAcrossStores() { final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE); stubProviderTwo.addStore(storeName, secondUnderlying); underlyingWindowStore.put("a", "a", 0L); secondUnderlying.put...
List<List<RingRange>> generateSplits(long totalSplitCount, List<BigInteger> ringTokens) { int tokenRangeCount = ringTokens.size(); List<RingRange> splits = new ArrayList<>(); for (int i = 0; i < tokenRangeCount; i++) { BigInteger start = ringTokens.get(i); BigInteger stop = ringTokens.get((i + ...
@Test(expected = RuntimeException.class) public void testDisorderedRing() { List<String> tokenStrings = Arrays.asList( "0", "113427455640312821154458202477256070485", "1", "56713727820156410577229101238628035242", "5671372782015641057722910123862...
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testMissedInvertedMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("something", "23"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test(expectedExceptions = EmptyStackException.class) public void testMissingOperand1And() { PredicateExpressionParser.parse("& com.linkedin.data.it.AlwaysFalsePredicate"); }
@Override public Optional<String> getContentHash() { return Optional.ofNullable(mContentHash); }
@Test public void flush() throws Exception { int partSize = (int) FormatUtils.parseSpaceSize(PARTITION_SIZE); byte[] b = new byte[2 * partSize - 1]; mStream.write(b, 0, b.length); Mockito.verify(mMockOssClient) .initiateMultipartUpload(any(InitiateMultipartUploadRequest.class)); Mockito.v...
public MethodInvoker getConstructor(Class<?> clazz, Class<?>[] parameters) { MethodDescriptor mDescriptor = new MethodDescriptor(clazz.getName(), clazz, parameters); MethodInvoker mInvoker = null; List<Constructor<?>> acceptableConstructors = null; LRUCache<MethodDescriptor, MethodInvoker> cache = cacheHolder.g...
@Test public void testGetConstructor() { ReflectionEngine engine = new ReflectionEngine(); MethodInvoker mInvoker = engine.getConstructor("p1.Cat", new Object[] {}); assertArrayEquals(mInvoker.getConstructor().getParameterTypes(), new Class[] {}); // Test cache: mInvoker = engine.getConstructor("p1.Cat", ne...
@Override public CloseableIterator<ScannerReport.Measure> readComponentMeasures(int componentRef) { ensureInitialized(); return delegate.readComponentMeasures(componentRef); }
@Test public void readComponentMeasures_is_not_cached() { writer.appendComponentMeasure(COMPONENT_REF, MEASURE); assertThat(underTest.readComponentMeasures(COMPONENT_REF)).isNotSameAs(underTest.readComponentMeasures(COMPONENT_REF)); }
public int allocate(final String label) { return allocate(label, DEFAULT_TYPE_ID); }
@Test void shouldStoreMetaData() { final int typeIdOne = 333; final long keyOne = 777L; final int typeIdTwo = 222; final long keyTwo = 444; final int counterIdOne = manager.allocate("Test Label One", typeIdOne, (buffer) -> buffer.putLong(0, keyOne)); final int c...
@Override public void notifyClientDisconnected(final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) { LOG.debug("Notifying MQTT client disconnection to interceptor. CId={}, username={}, interceptorId={}", ...
@Test public void testNotifyClientDisconnected() throws Exception { interceptor.notifyClientDisconnected("cli1234", "cli1234"); interval(); assertEquals(50, n.get()); }
@JsonCreator public static ModelVersion of(String version) { Preconditions.checkArgument(StringUtils.isNotBlank(version), "Version must not be blank"); return new AutoValue_ModelVersion(version); }
@Test public void deserialize() { final ModelVersion modelVersion = ModelVersion.of("foobar"); final JsonNode jsonNode = objectMapper.convertValue(modelVersion, JsonNode.class); assertThat(jsonNode.isTextual()).isTrue(); assertThat(jsonNode.asText()).isEqualTo("foobar"); }
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); gauges.put("name", (Gauge<String>) runtime::getName); gauges.put("vendor", (Gauge<String>) () -> String.format(Locale.US, "%s %s %s (%s)", runtime.getVmVen...
@Test public void hasAGaugeForTheJVMName() { final Gauge<String> gauge = (Gauge<String>) gauges.getMetrics().get("name"); assertThat(gauge.getValue()) .isEqualTo("9928@example.com"); }
public static Builder newScheduledThreadPool() { return new Builder(); }
@Test public void throwsExceptionWhenCorePoolSizeLessThanOne() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> ContextAwareScheduledThreadPoolExecutor .newScheduledThreadPool() .corePoolSize(0) .build()); }
@Override public void startScheduling() { checkIdleSlotTimeout(); state.as(Created.class) .orElseThrow( () -> new IllegalStateException( "Can only start scheduling when being in Created st...
@Test void testNumRestartsMetric() throws Exception { final CompletableFuture<Gauge<Long>> numRestartsMetricFuture = new CompletableFuture<>(); final MetricRegistry metricRegistry = TestingMetricRegistry.builder() .setRegisterConsumer( ...
public void shutdown() { isShutdown = true; responseHandlerSupplier.shutdown(); for (ClientInvocation invocation : invocations.values()) { //connection manager and response handler threads are closed at this point. invocation.notifyExceptionWithOwnedPermission(new Hazelc...
@Test public void testInvokeUrgent_whenThereAreCompactSchemas_andClientIsNotInitializedOnCluster() { client.getMap("testMap").put("test", new EmployeeDTO()); UUID memberUuid = member.getLocalEndpoint().getUuid(); member.shutdown(); makeSureDisconnectedFromServer(client, memberUuid);...
@InvokeOnHeader(Web3jConstants.ETH_GET_UNCLE_COUNT_BY_BLOCK_NUMBER) void ethGetUncleCountByBlockNumber(Message message) throws IOException { DefaultBlockParameter atBlock = toDefaultBlockParameter(message.getHeader(Web3jConstants.AT_BLOCK, configuration::getAtBlock, String.class)); R...
@Test public void ethGetUncleCountByBlockNumberTest() throws Exception { EthGetUncleCountByBlockNumber response = Mockito.mock(EthGetUncleCountByBlockNumber.class); Mockito.when(mockWeb3j.ethGetUncleCountByBlockNumber(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(respo...
@Override public ProxyInvocationHandler parserInterfaceToProxy(Object target, String objectName) { // eliminate the bean without two phase annotation. Set<String> methodsToProxy = this.tccProxyTargetMethod(target); if (methodsToProxy.isEmpty()) { return null; } //...
@Test public void testNestTcc_required_new_should_rollback_commit() throws Exception { //given RootContext.unbind(); DefaultResourceManager.get(); DefaultResourceManager.mockResourceManager(BranchType.TCC, resourceManager); TransactionManagerHolder.set(transactionManager); ...
@Override public Connection connect(String url, Properties info) throws SQLException { // calciteConnection is initialized with an empty Beam schema, // we need to populate it with pipeline options, load table providers, etc return JdbcConnection.initialize((CalciteConnection) super.connect(url, info)); ...
@Test public void testInternalConnect_setDirectRunner() throws Exception { CalciteConnection connection = JdbcDriver.connect(BOUNDED_TABLE, PipelineOptionsFactory.create()); Statement statement = connection.createStatement(); assertEquals(0, statement.executeUpdate("SET runner = direct")); ass...
@Override public AdjacencyList subgraph(int[] vertices) { int[] v = vertices.clone(); Arrays.sort(v); AdjacencyList g = new AdjacencyList(v.length, digraph); for (int i = 0; i < v.length; i++) { Collection<Edge> edges = getEdges(v[i]); for (Edge edge ...
@Test public void testSubgraph() { System.out.println("subgraph digraph = false"); AdjacencyList graph = new AdjacencyList(8, false); graph.addEdge(0, 2); graph.addEdge(1, 7); graph.addEdge(2, 6); graph.addEdge(7, 4); graph.addEdge(3, 4); graph.addEdg...
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingDeleteJsonRowNewRowToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "transactionId", false, "1", "tableName...
@Override public ImmutableList<String> computeEntrypoint(List<String> jvmFlags) throws IOException { try (JarFile jarFile = new JarFile(jarPath.toFile())) { String mainClass = jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); if (mainClass == null) { thr...
@Test public void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJ...
@Override public TwoFactorToken getToken(String userId, String operation) { return new TwoFactorToken() { private static final long serialVersionUID = -5148037320548431456L; @Override public void generate(long timeout) { TwoFactorTokenInfo info = new Two...
@Test @SneakyThrows public void test() { TwoFactorToken twoFactorToken = tokenManager.getToken("test", "test"); Assert.assertTrue(twoFactorToken.expired()); twoFactorToken.generate(1000L); Assert.assertFalse(twoFactorToken.expired()); Thread.sleep(1100); Assert.a...
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetName() { FileNameAnalyzer instance = new FileNameAnalyzer(); String expResult = "File Name Analyzer"; String result = instance.getName(); assertEquals(expResult, result); }
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenDatetimeWithSurroundingSpaces() { Instant datetime = Instant.parse("1234-01-23T10:00:05.000Z"); DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" 1234-01-23T10:00:05.000Z ", datetime); Schema schema = Schema.builder().addDateTimeField("a_datetime").addS...
public IndexConfig setType(IndexType type) { this.type = checkNotNull(type, "Index type cannot be null."); return this; }
@Test(expected = NullPointerException.class) public void testTypeNull() { new IndexConfig().setType(null); }