focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext, final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon...
@Test void assertNewInstanceForCloseAllStatement() { CloseStatementContext closeStatementContext = mock(CloseStatementContext.class, RETURNS_DEEP_STUBS); OpenGaussCloseStatement closeStatement = mock(OpenGaussCloseStatement.class); when(closeStatement.isCloseAll()).thenReturn(true); ...
@Override public void register(@NonNull Scheme scheme) { if (!schemes.contains(scheme)) { indexSpecRegistry.indexFor(scheme); schemes.add(scheme); getWatchers().forEach(watcher -> watcher.onChange(new SchemeRegistered(scheme))); } }
@Test void shouldTriggerOnChangeOnlyOnceWhenRegisterTwice() { final var watcher = mock(SchemeWatcher.class); when(watcherManager.watchers()).thenReturn(List.of(watcher)); schemeManager.register(FakeExtension.class); verify(watcherManager, times(1)).watchers(); verify(watcher...
@Override public void startScheduling() { Set<ExecutionVertexID> sourceVertices = IterableUtils.toStream(schedulingTopology.getVertices()) .filter(vertex -> vertex.getConsumedPartitionGroups().isEmpty()) .map(SchedulingExecutionVertex::getId) ...
@Test void testScheduleDownstreamOfHybridEdge() { final TestingSchedulingTopology topology = new TestingSchedulingTopology(); final List<TestingSchedulingExecutionVertex> producers = topology.addExecutionVertices().withParallelism(2).finish(); final List<TestingSchedulingEx...
public long getReportIntervalMs() { String intervalString = properties.getProperty( CONFLUENT_SUPPORT_METRICS_REPORT_INTERVAL_HOURS_CONFIG ); if (intervalString == null || intervalString.isEmpty()) { intervalString = CONFLUENT_SUPPORT_METRICS_REPORT_INTERVAL_HOURS_DEFAULT; ...
@Test public void testOverrideReportInterval() { // Given Properties overrideProps = new Properties(); int reportIntervalHours = 1; overrideProps.setProperty( BaseSupportConfig.CONFLUENT_SUPPORT_METRICS_REPORT_INTERVAL_HOURS_CONFIG, String.valueOf(reportIntervalHours) ); // Whe...
@Override public void reset() { // reset all offsets this.numRecords = 0; this.currentSortIndexOffset = 0; this.currentDataBufferOffset = 0; this.sortIndexBytes = 0; // return all memory this.freeMemory.addAll(this.sortIndex); this.freeMemory.addAll(t...
@Test void testReset() throws Exception { final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE; final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments); NormalizedKeySorter<Tuple2<Integer, String>> sorter = newSortBuffer(memor...
@Override public void run() { if (processedEvents.get() > 0) { LOG.debug("checkpointing offset after reaching timeout, with a batch of {}", processedEvents.get()); eventContext.updateCheckpointAsync() .subscribe(unused -> LOG.debug("Processed one event..."), ...
@Test void testProcessedEventsNotResetWhenCheckpointUpdateFails() { var processedEvents = new AtomicInteger(1); var eventContext = Mockito.mock(EventContext.class); Mockito.when(eventContext.updateCheckpointAsync()) .thenReturn(Mono.error(new RuntimeException())); v...
@Override public <T> AsyncResult<T> startProcess(Callable<T> task) { return startProcess(task, null); }
@Test void testNullTaskWithNullCallback() { assertTimeout(ofMillis(3000), () -> { // Instantiate a new executor and start a new 'null' task ... final var executor = new ThreadAsyncExecutor(); final var asyncResult = executor.startProcess(null, null); assertNotNull( asyncResult, ...
public synchronized void lockMQPeriodically() { if (!this.stopped) { this.defaultMQPushConsumerImpl.getRebalanceImpl().lockAll(); } }
@Test public void testLockMQPeriodically() { popService.lockMQPeriodically(); verify(defaultMQPushConsumerImpl, times(1)).getRebalanceImpl(); verify(rebalanceImpl, times(1)).lockAll(); }
static Entry<ScramMechanism, String> parsePerMechanismArgument(String input) { input = input.trim(); int equalsIndex = input.indexOf('='); if (equalsIndex < 0) { throw new FormatterException("Failed to find equals sign in SCRAM " + "argument '" + input + "'"); ...
@Test public void testParsePerMechanismArgumentWithConfigStringWithoutEndBrace() { assertEquals("Expected configuration string to end with ]", assertThrows(FormatterException.class, () -> ScramParser.parsePerMechanismArgument( "SCRAM-SHA-256=[name=scram-admin,...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final JsonNode event; try { event = objectMapper.readTree(payload); if (event == null || event.isMissingNode()) { throw new ...
@Test public void decodeMessagesHandlesGenericBeatWithCloudGCE() throws Exception { final Message message = codec.decode(messageFromJson("generic-with-cloud-gce.json")); assertThat(message).isNotNull(); assertThat(message.getMessage()).isEqualTo("-"); assertThat(message.getSource())....
@Override protected ExecuteContext doAfter(ExecuteContext context) { final Class<?> type = (Class<?>) context.getMemberFieldValue("type"); if (type == null) { return context; } if (canInjectClusterInvoker(type.getName()) && isDefined.compareAndSet(false, true)) { ...
@Test public void testNoExecute() throws NoSuchMethodException { final ExtensionLoaderInterceptor interceptor = new ExtensionLoaderInterceptor(); final HashMap<String, Class<?>> result = new HashMap<>(); interceptor.doAfter(buildContext(null, result)); Assert.assertTrue(result.isEmpt...
public static File getPath() { if (PATH == null) { PATH = findPath(); } return PATH; }
@Test public void testPath() { Assertions.assertTrue(WorkPath.getPath().exists()); }
Converter<E> compile() { head = tail = null; for (Node n = top; n != null; n = n.next) { switch (n.type) { case Node.LITERAL: addToList(new LiteralConverter<E>((String) n.getValue())); break; case Node.COMPOSITE_KEYWORD: CompositeNode cn = (CompositeNode) n; ...
@Test public void testComposite() throws Exception { // { // Parser<Object> p = new Parser<Object>("%(ABC)"); // p.setContext(context); // Node t = p.parse(); // Converter<Object> head = p.compile(t, converterMap); // String result = write(head, new Object()); // assertEquals("ABC", r...
protected boolean checkTabletReportCacheUp(long timeMs) { for (Backend backend : GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo().getBackends()) { if (TimeUtils.timeStringToLong(backend.getBackendStatus().lastSuccessReportTabletsTime) < timeMs) { LOG...
@Test public void testCheckTabletReportCacheUp() { long timeMs = System.currentTimeMillis(); MetaRecoveryDaemon metaRecoveryDaemon = new MetaRecoveryDaemon(); for (Backend backend : GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo().getBackends()) { backend.getBackend...
@Override public void reserveSegments(int numberOfSegmentsToReserve) throws IOException { checkArgument( numberOfSegmentsToReserve <= numberOfRequiredMemorySegments, "Can not reserve more segments than number of required segments."); CompletableFuture<?> toNotify = n...
@Test void testReserveSegments() throws Exception { NetworkBufferPool networkBufferPool = new NetworkBufferPool(2, memorySegmentSize, Duration.ofSeconds(2)); try { BufferPool bufferPool1 = networkBufferPool.createBufferPool(1, 2); assertThatThrownBy(() -> buff...
public static boolean isTrackInstallation() { try { return SAStoreManager.getInstance().isExists(SHARED_PREF_CORRECT_TRACK_INSTALLATION); } catch (Exception e) { SALog.printStackTrace(e); } return false; }
@Test public void isTrackInstallation() { }
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowFunctionStatusStatement) { return Optional.of(new ShowFunctionStatusExecutor((ShowFu...
@Test void assertCreateWithSetStatement() { when(sqlStatementContext.getSqlStatement()).thenReturn(new MySQLSetStatement()); Optional<DatabaseAdminExecutor> actual = new MySQLAdminExecutorCreator().create(sqlStatementContext, "", "", Collections.emptyList()); assertTrue(actual.isPresent()); ...
public void next() { index++; if (index > lineLength) { lineIndex++; if (lineIndex < lines.size()) { setLine(lines.get(lineIndex)); } else { setLine(SourceLine.of("", null)); } index = 0; } }
@Test public void testNext() { Scanner scanner = new Scanner(List.of( SourceLine.of("foo bar", null)), 0, 4); assertEquals('b', scanner.peek()); scanner.next(); assertEquals('a', scanner.peek()); scanner.next(); assertEquals('r', scanne...
@Override public void run() { try { PushDataWrapper wrapper = generatePushData(); ClientManager clientManager = delayTaskEngine.getClientManager(); for (String each : getTargetClientIds()) { Client client = clientManager.getClient(each); if...
@Test void testRunFailedWithNoRetry() { PushDelayTask delayTask = new PushDelayTask(service, 0L); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); pushExecutor.setShouldSuccess(false); pushExecutor.setFailedException(new NoRequiredRetryEx...
public void handleLoss(String loss) { lossHandler.accept(new UnwritableMetadataException(requestedMetadataVersion, loss)); }
@Test public void testDefaultLossHandler() { ImageWriterOptions options = new ImageWriterOptions.Builder().build(); assertEquals("stuff", assertThrows(UnwritableMetadataException.class, () -> options.handleLoss("stuff")).loss()); }
@Override public UnregisterBrokerResult unregisterBroker(int brokerId, UnregisterBrokerOptions options) { final KafkaFutureImpl<Void> future = new KafkaFutureImpl<>(); final long now = time.milliseconds(); final Call call = new Call("unregisterBroker", calcDeadlineMs(now, options.timeoutMs()...
@Test public void testUnregisterBrokerTimeoutAndFailureRetry() { int nodeId = 1; try (final AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions( NodeApiVersions.create(ApiKeys.UNREGISTER_BROKER.id, (short) 0, (short) 0)); e...
public String getSymbol() { final StringBuilder symbolic = new StringBuilder(); symbolic.append(setuid ? user.implies(Action.execute) ? StringUtils.substring(user.symbolic, 0, 2) + "s" : StringUtils.substring(user.symbolic, 0, 2) + "S" : user.symbolic); symbolic.a...
@Test public void testSymbol() { Permission p1 = new Permission(777); assertEquals("rwxrwxrwx", p1.getSymbol()); Permission p2 = new Permission(666); assertEquals("rw-rw-rw-", p2.getSymbol()); }
private ListenableFuture<TbAlarmResult> clearAlarm(TbContext ctx, TbMsg msg, Alarm alarm) { ctx.logJsEvalRequest(); ListenableFuture<JsonNode> asyncDetails = buildAlarmDetails(msg, alarm.getDetails()); return Futures.transform(asyncDetails, details -> { ctx.logJsEvalResponse(); ...
@Test void alarmCanBeCleared() { initWithClearAlarmScript(); metadata.putValue("key", "value"); TbMsg msg = TbMsg.newMsg(TbMsgType.POST_TELEMETRY_REQUEST, msgOriginator, metadata, "{\"temperature\": 50}"); long oldEndDate = System.currentTimeMillis(); Alarm activeAlarm = Ala...
@Override protected void write(final PostgreSQLPacketPayload payload) { ByteBuf byteBuf = payload.getByteBuf(); for (DatabasePacket each : packets) { if (!(each instanceof PostgreSQLIdentifierPacket)) { each.write(payload); continue; } ...
@Test void assertWrite() { PostgreSQLIdentifierPacket identifierPacket = mock(PostgreSQLIdentifierPacket.class); when(identifierPacket.getIdentifier()).thenReturn(PostgreSQLMessagePacketType.READY_FOR_QUERY); PostgreSQLPacket nonIdentifierPacket = mock(PostgreSQLPacket.class); Postgr...
public static int dayOfWeek(Date date) { return DateTime.of(date).dayOfWeek(); }
@Test public void dayOfWeekTest() { final int dayOfWeek = DateUtil.dayOfWeek(DateUtil.parse("2018-03-07")); assertEquals(Calendar.WEDNESDAY, dayOfWeek); final Week week = DateUtil.dayOfWeekEnum(DateUtil.parse("2018-03-07")); assertEquals(Week.WEDNESDAY, week); }
@Override public RetryStrategy getNextRetryStrategy() { int nextRemainingRetries = remainingRetries - 1; Preconditions.checkState( nextRemainingRetries >= 0, "The number of remaining retries must not be negative"); long nextRetryDelayMillis = Math.min(2 * curr...
@Test void testRetryFailure() { assertThatThrownBy( () -> new ExponentialBackoffRetryStrategy( 0, Duration.ofMillis(20L), Duration.ofMillis(20L)) .getNextRetryStrat...
public void unloadPlugin(GoPluginBundleDescriptor descriptorOfRemovedPlugin) { Bundle bundle = descriptorOfRemovedPlugin.bundle(); if (bundle == null) { return; } for (GoPluginDescriptor pluginDescriptor : descriptorOfRemovedPlugin.descriptors()) { for (PluginCha...
@Test void shouldNotUnloadAPluginIfItsBundleIsNull() { GoPluginBundleDescriptor pluginDescriptor = mock(GoPluginBundleDescriptor.class); when(pluginDescriptor.bundle()).thenReturn(null); pluginLoader.unloadPlugin(pluginDescriptor); verifyNoMoreInteractions(pluginOSGiFramework); ...
public static String decoratorPath(final String contextPath) { return StringUtils.contains(contextPath, AdminConstants.URI_SUFFIX) ? contextPath : contextPath + AdminConstants.URI_SUFFIX; }
@Test public void testDecoratorPath() { String uri = PathUtils.decoratorPath(URI); assertThat(uri, is(URI + AdminConstants.URI_SUFFIX)); uri = PathUtils.decoratorPath(URI_WRAPPER); assertThat(uri, is(URI + AdminConstants.URI_SUFFIX)); }
@Transactional public AppNamespace createAppNamespaceInLocal(AppNamespace appNamespace) { return createAppNamespaceInLocal(appNamespace, true); }
@Test(expected = BadRequestException.class) @Sql(scripts = "/sql/appnamespaceservice/init-appnamespace.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testCreatePublicAppNamespaceExisted() { App...
public static Builder in(Table table) { return new Builder(table); }
@TestTemplate public void testWithMetadataMatching() { table .newAppend() .appendFile(FILE_A) .appendFile(FILE_B) .appendFile(FILE_C) .appendFile(FILE_D) .commit(); Iterable<DataFile> files = FindFiles.in(table) .withMetadataMatching(Express...
public synchronized int requestUpdateForTopic(String topic) { if (newTopics.contains(topic)) { return requestUpdateForNewTopics(); } else { return requestUpdate(false); } }
@Test public void testRequestUpdateForTopic() { long now = 10000; final String topic1 = "topic-1"; final String topic2 = "topic-2"; // Add the topics to the metadata. metadata.add(topic1, now); metadata.add(topic2, now); assertTrue(metadata.updateRequested()...
@Override public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) { final ModelId modelId = entityDescriptor.id(); return dataAdapterService.get(modelId.id()).map(dataAdapterDto -> exportNativeEntity(dataAdapterDto, entityDescriptorIds)); ...
@Test @MongoDBFixtures("LookupDataAdapterFacadeTest.json") public void collectEntity() { final EntityDescriptor descriptor = EntityDescriptor.create("5adf24a04b900a0fdb4e52c8", ModelTypes.LOOKUP_ADAPTER_V1); final EntityDescriptorIds entityDescriptorIds = EntityDescriptorIds.of(descriptor); ...
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request) throws Exception { BeamFnApi.ProcessBundleResponse.Builder response = BeamFnApi.ProcessBundleResponse.newBuilder(); BundleProcessor bundleProcessor = bundleProcessorCache.get( request, ...
@Test public void testPendingStateCallsBlockTillCompletion() throws Exception { BeamFnApi.ProcessBundleDescriptor processBundleDescriptor = BeamFnApi.ProcessBundleDescriptor.newBuilder() .putTransforms( "2L", RunnerApi.PTransform.newBuilder() ...
public static WindowBytesStoreSupplier persistentTimestampedWindowStore(final String name, final Duration retentionPeriod, final Duration windowSize, ...
@Test public void shouldThrowIfIPersistentTimestampedWindowStoreIfWindowSizeIsNegative() { final Exception e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentTimestampedWindowStore("anyName", ofMillis(0L), ofMillis(-1L), false)); assertEquals("windowSize cannot be negative", e.g...
@Override public Long createGroup(MemberGroupCreateReqVO createReqVO) { // 插入 MemberGroupDO group = MemberGroupConvert.INSTANCE.convert(createReqVO); memberGroupMapper.insert(group); // 返回 return group.getId(); }
@Test public void testCreateGroup_success() { // 准备参数 MemberGroupCreateReqVO reqVO = randomPojo(MemberGroupCreateReqVO.class, o -> o.setStatus(randomCommonStatus())); // 调用 Long groupId = groupService.createGroup(reqVO); // 断言 assertNotNull(groupId); ...
Set<Integer> changedLines() { return tracker.changedLines(); }
@Test public void count_single_added_line() throws IOException { String example = "diff --git a/file-b1.xoo b/file-b1.xoo\n" + "index 0000000..c2a9048\n" + "--- a/foo\n" + "+++ b/bar\n" + "@@ -0,0 +1 @@\n" + "+added line\n"; printDiff(example); assertThat(underTest.changedLi...
public NodeState getWantedState() { NodeState retiredState = new NodeState(node.getType(), State.RETIRED); // Don't let configure retired state override explicitly set Down and Maintenance. if (configuredRetired && wantedState.above(retiredState)) { return retiredState; } ...
@Test void retired_state_overrides_default_up_wanted_state() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(3).markNodeAsConfigRetired(1); NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1)); assertEquals(State.RETIRED, nodeInfo.getWantedState().ge...
@Override @Transactional(rollbackFor = Exception.class) public void updateCombinationActivity(CombinationActivityUpdateReqVO updateReqVO) { // 校验存在 CombinationActivityDO activityDO = validateCombinationActivityExists(updateReqVO.getId()); // 校验状态 if (ObjectUtil.equal(activityDO.g...
@Test public void testUpdateCombinationActivity_success() { // mock 数据 CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class); combinationActivityMapper.insert(dbCombinationActivity);// @Sql: 先插入出一条存在的数据 // 准备参数 CombinationActivityUpdateReqVO re...
@Override public ShowIndexStatement getSqlStatement() { return (ShowIndexStatement) super.getSqlStatement(); }
@Test void assertNewInstance() { MySQLShowIndexStatement sqlStatement = new MySQLShowIndexStatement(); sqlStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("tbl_1")))); ShowIndexStatementContext actual = new ShowIndexStatementContext(sqlStatement, Defau...
@Override public Optional<String> buildInsertOnDuplicateClause(final DataRecord dataRecord) { StringBuilder result = new StringBuilder("ON DUPLICATE KEY UPDATE "); PipelineSQLSegmentBuilder sqlSegmentBuilder = new PipelineSQLSegmentBuilder(getType()); result.append(dataRecord.getColumns().st...
@Test void assertBuildInsertOnDuplicateClause() { String actual = sqlBuilder.buildInsertOnDuplicateClause(mockDataRecord()).orElse(null); assertThat(actual, is("ON DUPLICATE KEY UPDATE c0=EXCLUDED.c0,c1=EXCLUDED.c1,c2=EXCLUDED.c2,c3=EXCLUDED.c3")); }
private Set<TimelineEntity> getEntities(Path dir, String entityType, TimelineEntityFilters filters, TimelineDataToRetrieve dataToRetrieve) throws IOException { // First sort the selected entities based on created/start time. Map<Long, Set<TimelineEntity>> sortedEntities = new TreeMap<>( ...
@Test void testGetEntitiesByRelations() throws Exception { // Get entities based on relatesTo. TimelineFilterList relatesTo = new TimelineFilterList(Operator.OR); Set<Object> relatesToIds = new HashSet<Object>(Arrays.asList((Object) "flow1")); relatesTo.addFilter(new TimelineKeyValuesFilter( ...
public static List<SubjectAlternativeName> getSubjectAlternativeNames(X509Certificate certificate) { try { byte[] extensionValue = certificate.getExtensionValue(SUBJECT_ALTERNATIVE_NAMES.getOId()); if (extensionValue == null) return List.of(); ASN1Encodable asn1Encodable = AS...
@Test void can_list_subject_alternative_names() { KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256); X500Principal subject = new X500Principal("CN=myservice"); SubjectAlternativeName san = new SubjectAlternativeName(DNS, "dns-san"); X509Certificate cert = X509Certifica...
public static String getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException { FileChecksums fileChecksums = CHECKSUM_CACHE.get(file); if (fileChecksums == null) { try (InputStream stream = Files.newInputStream(file.toPath())) { final MessageDige...
@Test public void testGetChecksum_FileNotFound() throws Exception { String algorithm = "MD5"; File file = new File("not a valid file"); Exception exception = Assert.assertThrows(IOException.class, () -> Checksum.getChecksum(algorithm, file)); assertTrue(exception.getMessage().contain...
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testMatchXmlXpath() { fail = true; run( "xml myXml = <root><foo>bar</foo><hello><text>hello \"world\"</text></hello><hello><text>hello \"moon\"</text></hello></root>", "match myXml //myXml2/root/text == '#notnull'" ); }
@Override public <T> ReducingState<T> getReducingState(ReducingStateDescriptor<T> stateProperties) { KeyedStateStore keyedStateStore = checkPreconditionsAndGetKeyedStateStore(stateProperties); stateProperties.initializeSerializerUnlessSet(this::createSerializer); return keyedStateStore.getRe...
@Test void testReducingStateInstantiation() throws Exception { final ExecutionConfig config = new ExecutionConfig(); config.getSerializerConfig().registerKryoType(Path.class); final AtomicReference<Object> descriptorCapture = new AtomicReference<>(); StreamingRuntimeContext contex...
@Description("Smallest IP address for a given IP prefix") @ScalarFunction("ip_subnet_min") @SqlType(StandardTypes.IPADDRESS) public static Slice ipSubnetMin(@SqlType(StandardTypes.IPPREFIX) Slice value) { return castFromIpPrefixToIpAddress(value); }
@Test public void testIpSubnetMin() { assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/24')", IPADDRESS, "1.2.3.0"); assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/32')", IPADDRESS, "1.2.3.4"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::"); as...
public StateStore getStore() { return store; }
@Test public void shouldGetVersionedStore() { givenWrapperWithVersionedStore(); assertThat(wrapper.getStore(), equalTo(versionedStore)); }
@Override public String parseProperty(String key, String value, PropertiesLookup properties) { log.trace("Parsing property '{}={}'", key, value); if (value != null) { initEncryptor(); Matcher matcher = PATTERN.matcher(value); while (matcher.find()) { ...
@Test public void testDecryptsPartiallyEncryptedProperty() { String parmValue = "tiger"; String encParmValue = format("%s%s%s", JASYPT_PREFIX_TOKEN, encryptor.encrypt(parmValue), JASYPT_SUFFIX_TOKEN); String expected = format("http://somehost:port/?param1=%s&param2=somethingelse", parmValue...
@Override public Map<PCollection<?>, ReplacementOutput> mapOutputs( Map<TupleTag<?>, PCollection<?>> outputs, OutputT newOutput) { throw new UnsupportedOperationException(message); }
@Test public void mapOutputThrows() { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage(message); factory.mapOutputs(Collections.emptyMap(), PDone.in(pipeline)); }
Plugin create(Options.Plugin plugin) { try { return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument()); } catch (IOException | URISyntaxException e) { throw new CucumberException(e); } }
@Test void instantiates_timeline_plugin_with_dir_arg() { PluginOption option = parse("timeline:" + tmp.toAbsolutePath()); plugin = fc.create(option); assertThat(plugin.getClass(), is(equalTo(TimelineFormatter.class))); }
protected Response getVipResponse(String version, String entityName, String acceptHeader, EurekaAccept eurekaAccept, Key.EntityType entityType) { if (!registry.shouldAllowAccess(false)) { return Response.status(Response.Status.FORBIDDEN).build(); } ...
@Test public void testFullVipGet() throws Exception { Response response = resource.getVipResponse( Version.V2.name(), vipName, MediaType.APPLICATION_JSON, EurekaAccept.full, Key.EntityType.VIP ); String json = S...
CachedLayer writeTarLayer(DescriptorDigest diffId, Blob compressedBlob) throws IOException { Files.createDirectories(cacheStorageFiles.getLocalDirectory()); Files.createDirectories(cacheStorageFiles.getTemporaryDirectory()); try (TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider()) { ...
@Test public void testWriteTarLayer() throws IOException { Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); DescriptorDigest diffId = getDigest(uncompressedLayerBlob).getDigest(); CachedLayer cachedLayer = cacheStorageWriter.writeTarLayer(diffId, compress(uncompressedLayerBlob));...
@Override protected void processOptions(LinkedList<String> args) throws IOException { CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, OPTION_FOLLOW_LINK, OPTION_FOLLOW_ARG_LINK, null); cf.parse(args); if (cf.getOpt(OPTION_FOLLOW_LINK)) { getOptions().setFollowLink(tru...
@Test public void processOptionsKnownUnknown() throws IOException { Find find = new Find(); find.setConf(conf); String args = "path -print -unknown -print"; try { find.processOptions(getArgs(args)); fail("Unknown expression not caught"); } catch (IOException e) { } }
public static InternalSchema reconcileSchema(Schema incomingSchema, InternalSchema oldTableSchema, boolean makeMissingFieldsNullable) { /* If incoming schema is null, we fall back on table schema. */ if (incomingSchema.getType() == Schema.Type.NULL) { return oldTableSchema; } InternalSchema inComi...
@Test public void testEvolutionSchemaFromNewAvroSchema() { Types.RecordType oldRecord = Types.RecordType.get( Types.Field.get(0, false, "id", Types.IntType.get()), Types.Field.get(1, true, "data", Types.StringType.get()), Types.Field.get(2, true, "preferences", Types.RecordType...
@ApiOperation(value = "Delete device profile (deleteDeviceProfile)", notes = "Deletes the device profile. Referencing non-existing device profile Id will cause an error. " + "Can't delete the device profile if it is referenced by existing devices." + TENANT_AUTHORITY_PARAGRAPH) @PreA...
@Test public void testDeleteDeviceProfile() throws Exception { DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Mockito.reset(tbClusterService, auditLogService); ...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 3) { onInvalidDataReceived(device, data); return; } final int responseCode = data.getIntValue(Data.FORMAT_UINT8, 0); final int requestCode = da...
@Test public void onSCOperationError() { final MutableData data = new MutableData(new byte[] { 0x10, 0x02, 0x02}); response.onDataReceived(null, data); assertFalse(success); assertEquals(2, errorCode); assertEquals(2, requestCode); assertNull(locations); }
@Override public UnregisterBrokerResult unregisterBroker(int brokerId, UnregisterBrokerOptions options) { final KafkaFutureImpl<Void> future = new KafkaFutureImpl<>(); final long now = time.milliseconds(); final Call call = new Call("unregisterBroker", calcDeadlineMs(now, options.timeoutMs()...
@Test public void testUnregisterBrokerTimeoutMaxWait() { int nodeId = 1; try (final AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions( NodeApiVersions.create(ApiKeys.UNREGISTER_BROKER.id, (short) 0, (short) 0)); Unregist...
public static <T> List<T> sub(List<T> list, int start, int end) { return ListUtil.sub(list, start, end); }
@Test public void subInput1PositiveNegativePositiveOutputArrayIndexOutOfBoundsException() { assertThrows(IndexOutOfBoundsException.class, () -> { // Arrange final List<Integer> list = new ArrayList<>(); list.add(null); final int start = 2_147_483_643; final int end = -2_147_483_648; final int step ...
@Override public void audit(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule) { Collection<ShardingAuditStrategyConfiguration> auditStrategies = getShardingAuditStrategies(queryContext.getSqlStatementContext(), rule); ...
@Test void assertCheckSuccessByDisableAuditNames() { when(auditStrategy.isAllowHintDisable()).thenReturn(true); RuleMetaData globalRuleMetaData = mock(RuleMetaData.class); new ShardingSQLAuditor().audit(new QueryContext(sqlStatementContext, "", Collections.emptyList(), hintValueContext, mock...
public static String SHA1(String data) { return SHA1(data.getBytes()); }
@Test public void testSHA1() throws Exception { String biezhiSHA1 = "2aa70e156cfa0d5928574ee2d8904fb1d9c74ea0"; Assert.assertEquals( biezhiSHA1, EncryptKit.SHA1("biezhi") ); Assert.assertEquals( biezhiSHA1, EncryptKit.SH...
@VisibleForTesting Object evaluate(final GenericRow row) { return term.getValue(new TermEvaluationContext(row)); }
@Test public void shouldEvaluateLogicalExpressions_and() { // Given: final Expression expression1 = new LogicalBinaryExpression( LogicalBinaryExpression.Type.AND, COL11, new BooleanLiteral(true) ); final Expression expression2 = new LogicalBinaryExpression( LogicalBinar...
@Override public void export(RegisterTypeEnum registerType) { if (this.exported) { return; } if (getScopeModel().isLifeCycleManagedExternally()) { // prepare model for reference getScopeModel().getDeployer().prepare(); } else { // ensu...
@Test void testExportWithoutRegistryConfig() { serviceWithoutRegistryConfig.export(); assertThat(serviceWithoutRegistryConfig.getExportedUrls(), hasSize(1)); URL url = serviceWithoutRegistryConfig.toUrl(); assertThat(url.getProtocol(), equalTo("mockprotocol2")); assertThat(u...
@Deprecated public synchronized <K, V> Topology addGlobalStore(final StoreBuilder<?> storeBuilder, final String sourceName, final Deserializer<K> keyDeserializer, ...
@Deprecated // testing old PAPI @Test public void shouldNotAllowToAddGlobalStoreWithSourceNameEqualsProcessorName() { when(globalStoreBuilder.name()).thenReturn("anyName"); assertThrows(TopologyException.class, () -> topology.addGlobalStore( globalStoreBuilder, "sameName"...
public static void checkProjectKey(String keyCandidate) { checkArgument(isValidProjectKey(keyCandidate), MALFORMED_KEY_MESSAGE, keyCandidate, ALLOWED_CHARACTERS_MESSAGE); }
@Test public void checkProjectKey_with_correct_keys() { ComponentKeys.checkProjectKey("abc"); ComponentKeys.checkProjectKey("a-b_1.:2"); }
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by( PredicateT predicate) { return new Filter<>(predicate); }
@Test @Category(NeedsRunner.class) public void testFilterByPredicateWithLambda() { PCollection<Integer> output = p.apply(Create.of(1, 2, 3, 4, 5, 6, 7)).apply(Filter.by(i -> i % 2 == 0)); PAssert.that(output).containsInAnyOrder(2, 4, 6); p.run(); }
@Override public void createPod(Pod pod) { checkNotNull(pod, ERR_NULL_POD); checkArgument(!Strings.isNullOrEmpty(pod.getMetadata().getUid()), ERR_NULL_POD_UID); kubevirtPodStore.createPod(pod); log.debug(String.format(MSG_POD, pod.getMetadata().getName(), MSG_CREATE...
@Test(expected = NullPointerException.class) public void testCreateNullPod() { target.createPod(null); }
private static String[] getBucketAndPrefix() throws InvalidConfException { URI uri = normalizeConfigPath(Config.aws_s3_path, "s3", "Config.aws_s3_path", true); String path = uri.getPath(); if (path.startsWith("/")) { // remove leading '/' for backwards compatibility path ...
@Test public void testGetBucketAndPrefix() throws Exception { String oldAwsS3Path = Config.aws_s3_path; SharedDataStorageVolumeMgr sdsvm = new SharedDataStorageVolumeMgr(); Config.aws_s3_path = "bucket/dir1/dir2"; String[] bucketAndPrefix1 = Deencapsulation.invoke(sdsvm, "getBucketA...
@VisibleForTesting void updateConfig( Configuration config, ConfigOption<List<String>> configOption, List<String> newValue) { final List<String> originalValue = config.getOptional(configOption).orElse(Collections.emptyList()); if (hasLocal(originalValue)) { L...
@Test void testNoUpdateConfig() { List<String> artifactList = Collections.singletonList("s3://my-bucket/my-artifact.jar"); Configuration config = new Configuration(); config.set(ArtifactFetchOptions.ARTIFACT_LIST, artifactList); artifactUploader.updateConfig(config, ArtifactFetchOpt...
public static byte[] toSeed(List<String> words, String passphrase) { Objects.requireNonNull(passphrase, "A null passphrase is not allowed."); // To create binary seed from mnemonic, we use PBKDF2 function // with mnemonic sentence (in UTF-8) used as a password and // string "mnemonic" +...
@Test(expected = NullPointerException.class) public void testNullPassphrase() { List<String> code = WHITESPACE_SPLITTER.splitToList("legal winner thank year wave sausage worth useful legal winner thank yellow"); MnemonicCode.toSeed(code, null); }
@Private public void handleEvent(JobHistoryEvent event) { synchronized (lock) { // If this is JobSubmitted Event, setup the writer if (event.getHistoryEvent().getEventType() == EventType.AM_STARTED) { try { AMStartedEvent amStartedEvent = (AMStartedEvent) event.getHist...
@Test (timeout=50000) public void testFirstFlushOnCompletionEvent() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.workDir); conf.setLong(MRJobConfig.MR_AM_HISTORY_COMPLETE_EVENT_FLUSH_TIMEOUT_MS, 60 * 100...
@Override public TableBuilder buildTable(TableIdentifier identifier, Schema schema) { return new ViewAwareTableBuilder(identifier, schema); }
@Test public void testCommitExceptionWithMessage() { TableIdentifier tableIdent = TableIdentifier.of("db", "tbl"); BaseTable table = (BaseTable) catalog.buildTable(tableIdent, SCHEMA).create(); TableOperations ops = table.operations(); TableMetadata metadataV1 = ops.current(); table.updateSchema(...
public void add() { add(1L, defaultPosition); }
@Test final void testAddPoint() { final String metricName = "unitTestCounter"; Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build(); Counter c = receiver.declareCounter(metricName, p); c.add(); Bucket b = receiver.getSnapshot(); final Ma...
@Override public long decrementAndGet(K key) { return complete(asyncCounterMap.decrementAndGet(key)); }
@Test public void testDecrementAndGet() { atomicCounterMap.put(KEY1, VALUE1); Long afterIncrement = atomicCounterMap.decrementAndGet(KEY1); assertThat(afterIncrement, is(VALUE1 - 1)); }
public static synchronized void configure(DataflowWorkerLoggingOptions options) { if (!initialized) { throw new RuntimeException("configure() called before initialize()"); } // For compatibility reason, we do not call SdkHarnessOptions.getConfiguredLoggerFromOptions // to config the logging for l...
@Test public void testWithWorkerConfigurationOverride() { DataflowWorkerLoggingOptions options = PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class); options.setDefaultWorkerLogLevel(DataflowWorkerLoggingOptions.Level.WARN); DataflowWorkerLoggingInitializer.configure(options); Logg...
public StatisticRange addAndSumDistinctValues(StatisticRange other) { double newDistinctValues = distinctValues + other.distinctValues; return expandRangeWithNewDistinct(newDistinctValues, other); }
@Test public void testAddAndSumDistinctValues() { assertEquals(unboundedRange(NaN).addAndSumDistinctValues(unboundedRange(NaN)), unboundedRange(NaN)); assertEquals(unboundedRange(NaN).addAndSumDistinctValues(unboundedRange(1)), unboundedRange(NaN)); assertEquals(unboundedRange(1).addAndS...
public Matrix aat() { Matrix C = new Matrix(m, m); C.mm(NO_TRANSPOSE, this, TRANSPOSE, this); C.uplo(LOWER); return C; }
@Test public void testAAT() { System.out.println("AAT"); Matrix c = matrix.aat(); assertEquals(c.nrow(), 3); assertEquals(c.ncol(), 3); for (int i = 0; i < C.length; i++) { for (int j = 0; j < C[i].length; j++) { assertEquals(C[i][j], c.get(i, j), ...
public void updateCheckboxes( EnumSet<RepositoryFilePermission> permissionEnumSet ) { updateCheckboxes( false, permissionEnumSet ); }
@Test public void testUpdateCheckboxesManagePermissionsAppropriateTrue() { permissionsCheckboxHandler.updateCheckboxes( true, EnumSet.of( RepositoryFilePermission.ACL_MANAGEMENT, RepositoryFilePermission.DELETE, RepositoryFilePermission.WRITE, RepositoryFilePermission.READ ) ); verify( readCheckbox, t...
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) { return containsAtLeastEntriesIn(accumulateMap("containsAtLeast", k0, v0, rest)); }
@Test public void containsAtLeastNotInOrder() { ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3); assertThat(actual).containsAtLeast("march", 3, "feb", 2); expectFailureWhenTestingThat(actual).containsAtLeast("march", 3, "feb", 2).inOrder(); assertFailureKeys( ...
@PutMapping(value = "/log") @Secured(action = ActionTypes.WRITE, resource = "nacos/admin", signType = SignType.CONSOLE) public String setLogLevel(@RequestParam String logName, @RequestParam String logLevel) { Loggers.setLogLevel(logName, logLevel); return HttpServletResponse.SC_OK + ""; }
@Test void testSetLogLevel() { String res = coreOpsController.setLogLevel("1", "info"); assertEquals("200", res); }
public Optional<String> findAlias(final String projectionName) { for (Projection each : projections) { if (each instanceof ShorthandProjection) { Optional<Projection> projection = ((ShorthandProjection) each).getActualColumns().stream().filter(optional -> proj...
@Test void assertFindAlias() { Projection projection = getColumnProjectionWithAlias(); ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.singleton(projection)); assertTrue(projectionsContext.findAlias(projection.getExpression()).isPresent()); }
@Override public boolean tryRegister(ThreadPoolPlugin plugin) { return false; }
@Test public void testTryRegister() { Assert.assertFalse(manager.tryRegister(new TestPlugin())); }
public static List<SelectBufferResult> splitMessageBuffer(ByteBuffer cqBuffer, ByteBuffer msgBuffer) { if (cqBuffer == null || msgBuffer == null) { log.error("MessageFormatUtil split buffer error, cq buffer or msg buffer is null"); return new ArrayList<>(); } cqBuffer.r...
@Test public void testSplitMessages() { ByteBuffer msgBuffer1 = buildMockedMessageBuffer(); msgBuffer1.putLong(MessageFormatUtil.QUEUE_OFFSET_POSITION, 10); ByteBuffer msgBuffer2 = ByteBuffer.allocate(COMMIT_LOG_CODA_SIZE); msgBuffer2.putInt(MessageFormatUtil.COMMIT_LOG_CODA_SIZE); ...
public static long[] rowSums(int[][] matrix) { long[] x = new long[matrix.length]; for (int i = 0; i < x.length; i++) { x[i] = sum(matrix[i]); } return x; }
@Test public void testRowSums() { System.out.println("rowSums"); double[][] A = { {0.7220180, 0.07121225, 0.6881997}, {-0.2648886, -0.89044952, 0.3700456}, {-0.6391588, 0.44947578, 0.6240573} }; double[] r = {1.4814300, -0.7852925, 0.4343743}; ...
public String checkAuthenticationStatus(AdSession adSession, SamlSession samlSession, String artifact) throws BvdException, SamlSessionException, UnsupportedEncodingException, AdException { AdAuthenticationStatus status = AdAuthenticationStatus.valueOfLabel(adSession.getAuthenticationStatus()); if (sta...
@Test public void checkAuthenticationStatusCanceledTest() throws BvdException, AdException, SamlSessionException, UnsupportedEncodingException { AdSession adSession = new AdSession(); adSession.setAuthenticationStatus(AdAuthenticationStatus.STATUS_CANCELED.label); SamlSession samlSession = ...
public abstract Map<String, SubClusterPolicyConfiguration> getPoliciesConfigurations() throws Exception;
@Test public void testGetPoliciesConfigurations() throws YarnException { Map<String, SubClusterPolicyConfiguration> queuePolicies = facade.getPoliciesConfigurations(); for (String queue : queuePolicies.keySet()) { SubClusterPolicyConfiguration expectedPC = stateStoreTestUtil.queryPolicyConfigura...
@Override public TopologyGraph getGraph(Topology topology) { return defaultTopology(topology).getGraph(); }
@Test public void testGetGraph() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); ...
@Override synchronized Long headRecordOffset(final TopicPartition partition) { return wrapped.headRecordOffset(partition); }
@Test public void testHeadRecordOffset() { final TopicPartition partition = new TopicPartition("topic", 0); final Long recordOffset = 0L; when(wrapped.headRecordOffset(partition)).thenReturn(recordOffset); final Long result = synchronizedPartitionGroup.headRecordOffset(partition); ...
@VisibleForTesting Row transformInput(KafkaRecord<byte[], byte[]> record) { Row.FieldValueBuilder builder = Row.withSchema(getSchema()).withFieldValues(ImmutableMap.of()); if (schema.hasField(Schemas.MESSAGE_KEY_FIELD)) { builder.withFieldValue(Schemas.MESSAGE_KEY_FIELD, record.getKV().getKey()); } ...
@Test public void recordToRowFailures() { { Schema payloadSchema = Schema.builder().addStringField("def").build(); NestedPayloadKafkaTable table = newTable( Schema.builder() .addRowField(Schemas.PAYLOAD_FIELD, payloadSchema) .addField(Schemas...
@VisibleForTesting Pair<String, File> encryptSegmentIfNeeded(File tempDecryptedFile, File tempEncryptedFile, boolean isUploadedSegmentEncrypted, String crypterUsedInUploadedSegment, String crypterClassNameInTableConfig, String segmentName, String tableNameWithType) { boolean segmentNeedsEncryption = ...
@Test public void testEncryptSegmentIfNeededNoEncryption() { // arrange boolean uploadedSegmentIsEncrypted = false; String crypterClassNameInTableConfig = null; String crypterClassNameUsedInUploadedSegment = null; // act Pair<String, File> encryptionInfo = _resource .encryptSegmentIf...
@SuppressWarnings("checkstyle:MissingSwitchDefault") @Override protected void doCommit(TableMetadata base, TableMetadata metadata) { int version = currentVersion() + 1; CommitStatus commitStatus = CommitStatus.FAILURE; /* This method adds no fs scheme, and it persists in HTS that way. */ final Stri...
@Test void testDoCommitCherryPickSnapshotBaseUnchanged() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); List<Snapshot> testWapSnapshots = IcebergTestUtil.getWapSnapshots(); // add 1 snapshot and 1 staged snapshot to the base metadata TableMetadata base = Ta...
@Override public V takeFirst() throws InterruptedException { return commandExecutor.getInterrupted(takeFirstAsync()); }
@Test public void testTakeFirstAwait() throws InterruptedException { RBlockingDeque<Integer> deque = redisson.getPriorityBlockingDeque("queue:take"); Executors.newSingleThreadScheduledExecutor().schedule(() -> { RBlockingDeque<Integer> deque1 = redisson.getBlockingDeque("queue:take"); ...
@Override @Deprecated public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransf...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullStoreNamesOnFlatTransformValuesWithFlatValueSupplierAndNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatTransformValues( flatValueTr...
public byte[] getNextTag() { byte[] tagBytes = null; if (tagPool != null) { tagBytes = tagPool.pollFirst(); } if (tagBytes == null) { long tag = nextTagId++; int size = encodingSize(tag); tagBytes = new byte[size]; for (int ...
@Test public void testNewTagsOnSuccessiveCheckouts() { AmqpTransferTagGenerator tagGen = new AmqpTransferTagGenerator(true); byte[] tag1 = tagGen.getNextTag(); byte[] tag2 = tagGen.getNextTag(); byte[] tag3 = tagGen.getNextTag(); assertNotSame(tag1, tag2); assertNot...
@CanIgnoreReturnValue public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) { List<@Nullable Object> expected = (varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs); return containsExactlyElementsIn( expected, varargs != null && varargs.length == 1...
@Test public void iterableContainsExactlyWithMany() { assertThat(asList(1, 2, 3)).containsExactly(1, 2, 3); }
public static boolean isEditionBundled(Plugin plugin) { return SONARSOURCE_ORGANIZATION.equalsIgnoreCase(plugin.getOrganization()) && Arrays.stream(SONARSOURCE_COMMERCIAL_LICENSES).anyMatch(s -> s.equalsIgnoreCase(plugin.getLicense())); }
@Test public void isEditionBundled_on_PluginINfo_returns_true_for_organization_SonarSource_and_license_Commercial_case_insensitive() { PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isTrue(); }
@Override @Nullable public Object convert(String value) { if (value == null || value.isEmpty()) { return null; } final Parser parser = new Parser(timeZone.toTimeZone()); final List<DateGroup> r = parser.parse(value); if (r.isEmpty() || r.get(0).getDates().is...
@Test public void convertUsesEtcUTCIfTimeZoneSettingIsNotAString() throws Exception { Converter c = new FlexibleDateConverter(ImmutableMap.<String, Object>of("time_zone", 42)); final DateTime dateOnly = (DateTime) c.convert("2014-3-12"); assertThat(dateOnly.getZone()).isEqualTo(DateTimeZone...
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException { ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null")); if (null == value) { return convertNullValue(co...
@Test void assertConvertURLValueError() { String urlString = "no-exist:shardingsphere.apache.org/"; assertThrows(UnsupportedDataTypeConversionException.class, () -> ResultSetUtils.convertValue(urlString, URL.class)); }
@Override public String toString(final RouteUnit routeUnit) { return identifier.getQuoteCharacter().wrap(getConstraintValue(routeUnit)); }
@Test void assertUpperCaseToString() { SQLStatementContext sqlStatementContext = mockSQLStatementContext(); assertThat(new ConstraintToken(0, 1, new IdentifierValue("uc"), sqlStatementContext, mock(ShardingRule.class)).toString(getRouteUnit()), is("uc_t_order_0")); }
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { if ( dbMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) ); } ...
@Test public void testGetLegacyColumnNameDriverLessOrEqualToThreeFieldMySQL() throws Exception { DatabaseMetaData databaseMetaData = mock( DatabaseMetaData.class ); doReturn( 3 ).when( databaseMetaData ).getDriverMajorVersion(); assertEquals( "MySQL", new MySQLDatabaseMeta().getLegacyColumnName( database...
@ScalarOperator(LESS_THAN_OR_EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean lessThanOrEqual(@SqlType("unknown") boolean left, @SqlType("unknown") boolean right) { throw new AssertionError("value of unknown type should all be NULL"); }
@Test public void testLessThanOrEqual() { assertFunction("NULL <= NULL", BOOLEAN, null); }