focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean appliesTo(String pipelineName, String stageName) { boolean pipelineMatches = this.pipelineName.equals(pipelineName) || this.pipelineName.equals(GoConstants.ANY_PIPELINE); boolean stageMatches = this.stageName.equals(stageName) || this.stageName.equals(GoConstants.A...
@Test void anyPipelineAndAnyStageShouldAlwaysApply() { NotificationFilter filter = new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Breaks, false); assertThat(filter.appliesTo("cruise2", "dev")).isTrue(); }
@Override public final void filter(DiscFilterRequest request, ResponseHandler handler) { filter(request) .ifPresent(errorResponse -> writeResponse(request, errorResponse, handler)); }
@Test void filter_renders_errors_as_json() throws IOException { int statusCode = 403; String message = "Forbidden"; DiscFilterRequest request = FilterTestUtils.newRequestBuilder().build(); SimpleSecurityRequestFilter filter = new SimpleSecurityRequestFilter(new JsonSe...
@Override public String getSecurityLevel() { return securityLevel; }
@Test public void testGetSecurityLevel() { assertEquals(securityLevel, defaultSnmpv3Device.getSecurityLevel()); }
public void run() { runner = newJsonRunnerWithSetting( globalSettings.stream() .filter(byEnv(this.env)) .map(toRunnerSetting()) .collect(toList()), startArgs); runner.run(); }
@Test public void should_not_run_without_env() throws IOException { stream = getResourceAsStream("settings/env-settings.json"); runner = new SettingRunner(stream, createStartArgs(12306, "bar")); runner.run(); assertThrows(HttpResponseException.class, () -> { helper.get(r...
@Override public int getOrder() { return PluginEnum.CONTEXT_PATH.getCode(); }
@Test public void getOrderTest() { assertEquals(PluginEnum.CONTEXT_PATH.getCode(), contextPathPlugin.getOrder()); }
@VisibleForTesting Collection<PluginClassLoaderDef> defineClassloaders(Map<String, ExplodedPlugin> pluginsByKey) { Map<String, PluginClassLoaderDef> classloadersByBasePlugin = new HashMap<>(); for (ExplodedPlugin plugin : pluginsByKey.values()) { PluginInfo info = plugin.getPluginInfo(); String b...
@Test public void log_warning_if_plugin_is_built_with_api_5_2_or_lower() throws Exception { File jarFile = temp.newFile(); PluginInfo info = new PluginInfo("foo") .setJarFile(jarFile) .setMainClass("org.foo.FooPlugin") .setMinimalSonarPluginApiVersion(Version.create("4.5.2")); Collectio...
@Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { this.config = TbNodeUtils.convert(configuration, TbMsgDeleteAttributesNodeConfiguration.class); this.keys = config.getKeys(); }
@Test void givenMsg_whenOnMsg_thenVerifyOutput_SendAttributesDeletedNotification_NoNotifyDevice() throws Exception { config.setSendAttributesDeletedNotification(true); nodeConfiguration = new TbNodeConfiguration(JacksonUtil.valueToTree(config)); node.init(ctx, nodeConfiguration); onM...
void createIfMissing(String key, SelTypes type) { // won't create array if (symtab.containsKey(key)) { return; } else if (inputTab != null && inputTab.containsKey(key)) { Object inputVal = inputTab.get(key); SelType newVal = box(inputVal); symtab.put(key, newVal); } else { symt...
@Test public void createIfMissing() { state.resetWithInput(params, null); state.createIfMissing("foo", SelTypes.STRING); SelType res = state.get("foo"); assertEquals("STRING: bar", res.type() + ": " + res); state.createIfMissing("fuu", SelTypes.STRING); res = state.get("fuu"); assertEquals...
public String doLayout(ILoggingEvent event) { if (!isStarted()) { return CoreConstants.EMPTY_STRING; } return writeLoopOnConverters(event); }
@Test public void testWithLettersComingFromLog4j() { // Letters: p = level and c = logger pl.setPattern("%d %p [%t] %c{30} - %m%n"); pl.start(); String val = pl.doLayout(getEventObject()); // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some // me...
public static InputStream markSupportedInputStream(final InputStream is, final int markBufferSize) { if (is.markSupported()) { return is; } return new InputStream() { byte[] mMarkBuffer; boolean mInMarked = false; boolean mInReset = false; ...
@Test void testMarkSupportedInputStream() throws Exception { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); assertEquals(10, is.available()); is = new PushbackInputStream(is); assertEquals(10, is.available()); assertFalse(is.markSupported...
public int go(String inputFileName, String outputFileName, String processor, Flags flags, OfflineEditsVisitor visitor) { if (flags.getPrintToScreen()) { System.out.println("input [" + inputFileName + "]"); System.out.println("output [" + outputFileName + "]"); } boolean xmlInput = Str...
@Test public void testStatisticsStrWithNullOpCodeCount() throws IOException { String editFilename = nnHelper.generateEdits(); String outFilename = editFilename + ".stats"; FileOutputStream fout = new FileOutputStream(outFilename); StatisticsEditsVisitor visitor = new StatisticsEditsVisitor(fout); ...
static String calculateBillingProjectId(Optional<String> configParentProjectId, Optional<Credentials> credentials) { if (configParentProjectId.isPresent()) { return configParentProjectId.get(); } // All other credentials types (User, AppEngine, GCE, CloudShell, etc.) take it fro...
@Test public void testConfigurationOnly() throws Exception { String projectId = BigQueryConnectorModule.calculateBillingProjectId(Optional.of("pid"), Optional.empty()); assertThat(projectId).isEqualTo("pid"); }
public static boolean isBoxedPrimitive(@Nullable String desc) { return PRIMITIVE_BOXES.contains(desc); }
@Test void testIsPrimitiveBox() { for (Type primitive : Types.PRIMITIVES) { assertFalse(Types.isBoxedPrimitive(primitive.getDescriptor()), "Failed on: " + primitive); } for (String primitiveBox : Types.PRIMITIVE_BOXES) { assertTrue(Types.isBoxedPrimitive(primitiveBox), "Failed on: " + primitiveBox); } ...
public MijnDigidSessionStatus sessionStatus(String mijnDigiDSessionId) { Optional<MijnDigidSession> optionalSession = mijnDigiDSessionRepository.findById(mijnDigiDSessionId); if( optionalSession.isEmpty()) { return MijnDigidSessionStatus.INVALID; } MijnDigidSession session = ...
@Test void testStatusUnauthenticatedExistingSession() { MijnDigidSession session = new MijnDigidSession(1L); session.setAuthenticated(false); when(mijnDigiDSessionRepository.findById(eq(session.getId()))).thenReturn(Optional.of(session)); MijnDigidSessionStatus status = mijnDigiDSes...
@Override public String toString() { return String.format("%s.orFinally(%s)", subTriggers.get(ACTUAL), subTriggers.get(UNTIL)); }
@Test public void testToString() { TriggerStateMachine trigger = StubTriggerStateMachine.named("t1").orFinally(StubTriggerStateMachine.named("t2")); assertEquals("t1.orFinally(t2)", trigger.toString()); }
public Set<Long> calculateUsers(DelegateExecution execution, int level) { Assert.isTrue(level > 0, "level 必须大于 0"); // 获得发起人 ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId()); Long startUserId = NumberUtils.parseLong(processInst...
@Test public void testCalculateUsers_existParentDept() { // 准备参数 DelegateExecution execution = mockDelegateExecution(1L); // mock 方法(startUser) AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L)); when(adminUserApi.getUser(eq(1L))).thenRetur...
public String sprites() { return get(SPRITES, null); }
@Test(expected = InvalidFieldException.class) public void cantSetSpritesIfGeoIsSet() { cfg = cfgFromJson(tmpNode(GEOMAP)); cfg.sprites("sprites-name"); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseSpecificOverOnlyVarArgsReversedInsertionOrder() { // Given: givenFunctions( function(OTHER, 0, STRING_VARARGS), function(EXPECTED, -1, STRING, STRING, STRING, STRING) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableLis...
public static <F extends Future<Void>> Mono<Void> deferFuture(Supplier<F> deferredFuture) { return new DeferredFutureMono<>(deferredFuture); }
@Test void raceTestDeferredFutureMonoWithSuccess() { for (int i = 0; i < 1000; i++) { final TestSubscriber subscriber = new TestSubscriber(); final ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE; final Promise<Void> promise = eventExecutor.newPromise(); final Supplier<Promise<Void...
public static List<ProcessInformations> buildProcessInformations(InputStream in, boolean windows, boolean macOrAix) { final String charset; if (windows) { charset = "Cp1252"; } else { charset = "UTF-8"; } final Scanner sc = new Scanner(in, charset); sc.useRadix(10); sc.useLocale(Locale.US); sc....
@Test public void testExecuteAndReadPs() throws IOException { final List<ProcessInformations> processes = ProcessInformations.buildProcessInformations(); assertNotNull("processes null", processes); assertFalse("processes vide", processes.isEmpty()); final boolean windows = System.getProperty("os.name").toLower...
@Override public void close() throws Exception { super.close(); collector = null; triggerContext = null; if (windowAggregator != null) { windowAggregator.close(); } }
@Test public void testWindowCloseWithoutOpen() throws Exception { if (!UTC_ZONE_ID.equals(shiftTimeZone)) { return; } final int windowSize = 3; LogicalType[] windowTypes = new LogicalType[] {new BigIntType()}; WindowOperator operator = WindowOpera...
@Override public boolean canPass(Node node, int acquireCount) { return canPass(node, acquireCount, false); }
@Test public void testThrottlingControllerZeroThreshold() throws InterruptedException { ThrottlingController paceController = new ThrottlingController(500, 0d); Node node = mock(Node.class); for (int i = 0; i < 2; i++) { assertFalse(paceController.canPass(node, 1)); ...
@Override @NonNull public String getId() { return ID; }
@Test public void shouldFailForBadCredentialIdOnCreate() throws IOException, UnirestException { User user = login(); Map resp = createCredentials(user, MapsHelper.of("credentials", new MapsHelper.Builder<String,Object>() .put("privateKeySource", MapsHelper.of(...
@Override public String named() { return PluginEnum.WAF.getName(); }
@Test public void testNamed() { final String result = wafPluginUnderTest.named(); assertEquals(PluginEnum.WAF.getName(), result); }
public static KettleDatabaseBatchException createKettleDatabaseBatchException( String message, SQLException ex ) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException( message, ex ); if ( ex instanceof BatchUpdateException ) { kdbe.setUpdateCounts( ( (BatchUpdateException) ex ).getUpdateC...
@Test public void testCreateKettleDatabaseBatchExceptionConstructsExceptionList() { BatchUpdateException root = new BatchUpdateException(); SQLException next = new SQLException(); SQLException next2 = new SQLException(); root.setNextException( next ); next.setNextException( next2 ); List<Excep...
@Override public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId, final ProcessorContext context, final long streamTime) { final TimestampedSegment segment = super.getOrCreateSegmentIfLiv...
@Test public void shouldCleanupSegmentsThatHaveExpired() { final TimestampedSegment segment1 = segments.getOrCreateSegmentIfLive(0, context, -1L); final TimestampedSegment segment2 = segments.getOrCreateSegmentIfLive(1, context, -1L); final TimestampedSegment segment3 = segments.getOrCreateS...
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { SQLStatement dalStatement = sqlStatementContext.getSq...
@Test void assertMergeForShowIndexStatement() throws SQLException { DALStatement dalStatement = new MySQLShowIndexStatement(); SQLStatementContext sqlStatementContext = mockSQLStatementContext(dalStatement); ShardingDALResultMerger resultMerger = new ShardingDALResultMerger(DefaultDatabase.L...
public BrokerFileSystem getFileSystem(String path, Map<String, String> properties) { WildcardURI pathUri = new WildcardURI(path); String scheme = pathUri.getUri().getScheme(); if (Strings.isNullOrEmpty(scheme)) { throw new BrokerException(TBrokerOperationStatusCode.INVALID_INPUT_FILE...
@Test public void testGetFileSystemForMultipleNameServicesHA() throws IOException { Map<String, String> properties = new HashMap<String, String>(); properties.put("username", "user"); properties.put("password", "passwd"); properties.put("fs.defaultFS", "hdfs://starrocks"); pr...
@Override public Object intercept(final Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); //Elegant access to object properties through MetaObject, here is access to the properties of statementHandler; //MetaObject is an...
@Test public void interceptTest() { final PostgreSQLPrepareInterceptor postgreSQLPrepareInterceptor = new PostgreSQLPrepareInterceptor(); final Invocation invocation = mock(Invocation.class); final StatementHandler statementHandler = mock(StatementHandler.class); when(invocation.getT...
static Properties resolveProducerProperties(Map<String, String> options, Object keySchema, Object valueSchema) { Properties properties = from(options); withSerdeProducerProperties(true, options, keySchema, properties); withSerdeProducerProperties(false, options, valueSchema, properties); ...
@Test public void when_producerProperties_preferredLocalParallelismPropertyIsDefined_then_itIsIgnored() { assertThat(resolveProducerProperties(Map.of(OPTION_PREFERRED_LOCAL_PARALLELISM, "-1"))) .containsExactlyEntriesOf(Map.of(KEY_SERIALIZER, ByteArraySerializer.class.getCanonicalName())); ...
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@Test public void testPartitionedMonths() throws Exception { createPartitionedTable(spark, tableName, "months(ts)"); SparkScanBuilder builder = scanBuilder(); MonthsFunction.TimestampToMonthsFunction function = new MonthsFunction.TimestampToMonthsFunction(); UserDefinedScalarFunc udf = toUDF...
public GrpcChannel acquireChannel(GrpcNetworkGroup networkGroup, GrpcServerAddress serverAddress, AlluxioConfiguration conf, boolean alwaysEnableTLS) { GrpcChannelKey channelKey = getChannelKey(networkGroup, serverAddress, conf); CountingReference<ManagedChannel> channelRef = mChannels.compute(cha...
@Test public void testDifferentKeys() throws Exception { try (CloseableTestServer server1 = createServer(); CloseableTestServer server2 = createServer()) { GrpcChannel conn1 = GrpcChannelPool.INSTANCE.acquireChannel( GrpcNetworkGroup.RPC, server1.getConnectAddress(), sConf, false); G...
public StatMap<K> merge(K key, int value) { if (key.getType() == Type.LONG) { merge(key, (long) value); return this; } int oldValue = getInt(key); int newValue = key.merge(oldValue, value); if (newValue == 0) { _map.remove(key); } else { _map.put(key, newValue); } ...
@Test(dataProvider = "allTypeStats", expectedExceptions = IllegalArgumentException.class) public void dynamicTypeCheckWhenAddInt(MyStats stat) { if (stat.getType() == StatMap.Type.INT) { throw new SkipException("Skipping INT test"); } if (stat.getType() == StatMap.Type.LONG) { throw new SkipEx...
public static Object deep(Object o) { if (o == null) { return null; } final Class<?> cls = o.getClass(); final Valuefier.Converter converter = CONVERTER_MAP.get(cls); if (converter != null) { return converter.convert(o); } return fallbackCo...
@Test public void testRubyBignum() { RubyBignum v = RubyBignum.newBignum(RubyUtil.RUBY, "-9223372036854776000"); Object result = Javafier.deep(v); assertEquals(BigInteger.class, result.getClass()); assertEquals( "-9223372036854776000", result.toString()); }
public CompletableFuture<Integer> getCount(final UUID identifier, final byte deviceId) { final Timer.Sample sample = Timer.start(); return dynamoDbAsyncClient.query(QueryRequest.builder() .tableName(tableName) .consistentRead(false) .keyConditionExpression("#uuid = :uuid AND...
@Test void getCount() { final SingleUsePreKeyStore<K> preKeyStore = getPreKeyStore(); final UUID accountIdentifier = UUID.randomUUID(); final byte deviceId = 1; assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join()); final List<K> preKeys = generateRandomPreKeys(); preKe...
public void fetchBytesValues(String column, int[] inDocIds, int length, byte[][] outValues) { _columnValueReaderMap.get(column).readBytesValues(inDocIds, length, outValues); }
@Test public void testFetchBytesValues() { testFetchBytesValues(BYTES_COLUMN); testFetchBytesValues(NO_DICT_BYTES_COLUMN); testFetchBytesValues(STRING_COLUMN); testFetchBytesValues(NO_DICT_STRING_COLUMN); }
public static long betweenDay(Date beginDate, Date endDate, boolean isReset) { if (isReset) { beginDate = beginOfDay(beginDate); endDate = beginOfDay(endDate); } return between(beginDate, endDate, DateUnit.DAY); }
@Test public void betweenDayTest() { for (int i = 0; i < 1000; i++) { final String datr = RandomUtil.randomInt(1900, 2099) + "-01-20"; final long betweenDay = DateUtil.betweenDay( DateUtil.parseDate("1970-01-01"), DateUtil.parseDate(datr), false); assertEquals(Math.abs(LocalDate.parse(datr).toEpoc...
protected int getMaxUnconfirmedReads(final TransferStatus status) { final PreferencesReader preferences = new HostPreferences(session.getHost()); if(TransferStatus.UNKNOWN_LENGTH == status.getLength()) { return preferences.getInteger("sftp.read.maxunconfirmed"); } return Inte...
@Test public void testUnconfirmedReadsNumber() { final SFTPReadFeature feature = new SFTPReadFeature(session); assertEquals(33, feature.getMaxUnconfirmedReads(new TransferStatus().withLength(TransferStatus.MEGA * 1L))); assertEquals(64, feature.getMaxUnconfirmedReads(new TransferStatus().wit...
boolean valid(int nodeId, MetadataImage image) { TopicImage topicImage = image.topics().getTopic(topicIdPartition.topicId()); if (topicImage == null) { return false; // The topic has been deleted. } PartitionRegistration partition = topicImage.partitions().get(topicIdPartitio...
@Test public void testAssignmentForNonExistentTopicIsNotValid() { assertFalse(new Assignment( new TopicIdPartition(Uuid.fromString("uuOi4qGPSsuM0QwnYINvOw"), 0), Uuid.fromString("rzRT8XZaSbKsP6j238zogg"), 0, NoOpRunnable.INSTANCE).valid(0, TEST_IMAGE)); }
public ConvertedTime getConvertedTime(long duration) { Set<Seconds> keys = RULES.keySet(); for (Seconds seconds : keys) { if (duration <= seconds.getSeconds()) { return RULES.get(seconds).getConvertedTime(duration); } } return new TimeConverter.Ove...
@Test public void testShouldReport23HoursFor23Hours59Minutes29Seconds() throws Exception { assertEquals(TimeConverter.ABOUT_X_HOURS_AGO.argument(23), timeConverter .getConvertedTime(24 * TimeConverter.HOUR_IN_SECONDS - 31)); }
ConcurrentPublication addPublication(final String channel, final int streamId) { clientLock.lock(); try { ensureActive(); ensureNotReentrant(); final long registrationId = driverProxy.addPublication(channel, streamId); stashedChannelByRegistra...
@Test void addPublicationShouldNotifyMediaDriver() { whenReceiveBroadcastOnMessage( ControlProtocolEvents.ON_PUBLICATION_READY, publicationReadyBuffer, (buffer) -> publicationReady.length()); conductor.addPublication(CHANNEL, STREAM_ID_1); verify(dri...
@Override public URL getResource(String name) { ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resource '{}'", name); for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) { URL url = null; ...
@Test void parentLastGetResourceExistsOnlyInDependnecy() throws IOException, URISyntaxException { URL resource = parentLastPluginClassLoader.getResource("META-INF/dependency-file"); assertFirstLine("dependency", resource); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersion.class) || resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersions.class)) { checkVersion(...
@Test public void testFilterOnNeitherClassNorMethod() throws Exception { final Method resourceMethod = TestResourceWithOutAnnotation.class.getMethod("methodWithoutAnnotation"); final Class resourceClass = TestResourceWithOutAnnotation.class; when(resourceInfo.getResourceMethod()).thenReturn(...
@Nullable @Override public GenericRow decode(byte[] payload, GenericRow destination) { try { destination = (GenericRow) _decodeMethod.invoke(null, payload, destination); } catch (Exception e) { throw new RuntimeException(e); } return destination; }
@Test(dataProvider = "defaultCases") public void whenDefaultCases(String fieldName, Object protoValue, Object pinotVal) throws Exception { Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(fieldName); ComplexTypes.TestMessage.Builder messageBuilder = ComplexTypes....
public MapStoreConfig setClassName(@Nonnull String className) { this.className = checkHasText(className, "Map store class name must contain text"); this.implementation = null; return this; }
@Test public void setClassName() { assertEquals("some.class", cfgNonNullClassName.getClassName()); assertEquals(new MapStoreConfig().setClassName("some.class"), cfgNonNullClassName); }
public static void preserve(FileSystem targetFS, Path path, CopyListingFileStatus srcFileStatus, EnumSet<FileAttribute> attributes, boolean preserveRawXattrs) throws IOException { // strip out those attributes we don't need a...
@Test public void testPreserveUserOnDirectory() throws IOException { FileSystem fs = FileSystem.get(config); EnumSet<FileAttribute> attributes = EnumSet.of(FileAttribute.USER); Path dst = new Path("/tmp/abc"); Path src = new Path("/tmp/src"); createDirectory(fs, src); createDirectory(fs, dst...
public static String getProperty(final String propertyName) { final String propertyValue = System.getProperty(propertyName); return NULL_PROPERTY_VALUE.equals(propertyValue) ? null : propertyValue; }
@Test void shouldGetNormalProperty() { final String key = "org.agrona.test.case"; final String value = "wibble"; System.setProperty(key, value); try { assertEquals(value, SystemUtil.getProperty(key)); } finally { System.cl...
@Operation(summary = "queryResourceList", description = "QUERY_RESOURCE_LIST_NOTES") @Parameters({ @Parameter(name = "type", description = "RESOURCE_TYPE", required = true, schema = @Schema(implementation = ResourceType.class)), @Parameter(name = "fullName", description = "RESOURCE_FULLNAME"...
@Test public void testQuerytResourceList() throws Exception { Map<String, Object> mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); Mockito.when(resourcesService.queryResourceList(Mockito.any(), Mockito.any(), Mockito.anyString())) .thenReturn(mo...
@Override public Table getTable(long id, String name, List<Column> schema, String dbName, String catalogName, Map<String, String> properties) throws DdlException { Map<String, String> newProp = new HashMap<>(properties); newProp.putIfAbsent(JDBCTable.JDBC_TABLENAME, "[" + d...
@Test public void testGetTable() throws SQLException { new Expectations() { { dataSource.getConnection(); result = connection; minTimes = 0; connection.getCatalog(); result = "t1"; minTimes = 0; ...
@Override public ChannelFuture writePushPromise(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding, ChannelPromise promise) { try { if (connection.goAwayReceived()) { throw connectionError(PROTOCOL_ERROR, "Sending PUSH_PRO...
@Test public void pushPromiseWriteAfterGoAwayReceivedShouldFail() throws Exception { createStream(STREAM_ID, false); goAwayReceived(0); ChannelFuture future = encoder.writePushPromise(ctx, STREAM_ID, PUSH_STREAM_ID, EmptyHttp2Headers.INSTANCE, 0, newPromise()); assert...
@PutMapping @Secured(action = ActionTypes.WRITE) public String update(HttpServletRequest request) throws Exception { final String namespaceId = WebUtils .optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); final String clusterName = WebUtils.required(req...
@Test void testUpdate() throws Exception { mockRequestParameter(CommonParams.NAMESPACE_ID, "test-namespace"); mockRequestParameter(CommonParams.CLUSTER_NAME, TEST_CLUSTER_NAME); mockRequestParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); mockRequestParameter("checkPort", "1")...
public boolean equals(Object obj) { return this == obj; // this is correct because there are only two COSBoolean objects. }
@Test void testEquals() { COSBoolean test1 = COSBoolean.TRUE; COSBoolean test2 = COSBoolean.TRUE; COSBoolean test3 = COSBoolean.TRUE; // Reflexive (x == x) assertEquals(test1, test1); // Symmetric is preserved ( x==y then y===x) assertEquals(test2, test1);...
public String webURL() { return DEFAULT_WEB_URL; }
@Test public void default_webUrl() { assertThat(underTest.webURL()).isEqualTo("https://bitbucket.org/"); }
public boolean update(final String profileId, final IndexFieldTypeProfile updatedProfile) { if (!ObjectId.isValid(profileId)) { return false; } updatedProfile.customFieldMappings().forEach(mapping -> checkFieldTypeCanBeChanged(mapping.fieldName())); final WriteResult<IndexFie...
@Test public void testUpdate() { final IndexFieldTypeProfile profile = new IndexFieldTypeProfile("123400000000000000000001", "profile", "profile", new CustomFieldMappings()); toTest.save(profile); final IndexFieldTypeProfile updatedProfile = new IndexFieldTypeProfile(profile.id(), "Changed!...
public static long readUint32BE(ByteBuffer buf) throws BufferUnderflowException { return Integer.toUnsignedLong(buf.order(ByteOrder.BIG_ENDIAN).getInt()); }
@Test public void testReadUInt32BE() { assertEquals(258L, ByteUtils.readUint32BE(new byte[]{0, 0, 1, 2}, 0)); assertEquals(258L, ByteUtils.readUint32BE(new byte[]{0, 0, 1, 2, 3, 4}, 0)); assertEquals(772L, ByteUtils.readUint32BE(new byte[]{1, 2, 0, 0, 3, 4}, 2)); }
public static String encodeForRegistry(String element) { return IDN.toASCII(element); }
@Test public void testFormatIdempotent() throws Throwable { assertConverted("xn--lzg", RegistryPathUtils.encodeForRegistry(EURO)); }
@UdafFactory(description = "collect values of a field into a single Array") public static <T> TableUdaf<T, List<T>, List<T>> createCollectListT() { return new Collect<>(); }
@Test public void shouldCollectTimes() { final TableUdaf<Time, List<Time>, List<Time>> udaf = CollectListUdaf.createCollectListT(); final Time[] values = new Time[] {new Time(1), new Time(2)}; List<Time> runningList = udaf.initialize(); for (final Time i : values) { runningList = udaf.aggregate(...
@Override public TaskExecutor executor() { return new JsonBasedTaskExecutor(pluginId, pluginRequestHelper, handlerMap); }
@Test public void shouldGetTaskExecutor() { assertTrue(task.executor() instanceof JsonBasedTaskExecutor); }
public static <K, V> KvCoder<K, V> of(Coder<K> keyCoder, Coder<V> valueCoder) { return new KvCoder<>(keyCoder, valueCoder); }
@Test public void testCoderIsSerializableWithWellKnownCoderType() throws Exception { CoderProperties.coderSerializable( KvCoder.of(GlobalWindow.Coder.INSTANCE, GlobalWindow.Coder.INSTANCE)); }
public static org.apache.avro.Schema toAvroSchema( Schema beamSchema, @Nullable String name, @Nullable String namespace) { final String schemaName = Strings.isNullOrEmpty(name) ? "topLevelRecord" : name; final String schemaNamespace = namespace == null ? "" : namespace; String childNamespace = ...
@Test public void testAvroSchemaFromBeamSchemaWithFieldCollisionCanBeParsed() { // Two similar schemas, the only difference is the "street" field type in the nested record. Schema contact = new Schema.Builder() .addField(Field.of("name", FieldType.STRING)) .addField( ...
@Override public O next() { if (!hasNext()) { throw new NoSuchElementException(); } O result = nextObject; nextObject = null; return result; }
@Test public void call_next_without_hasNext() { SimpleCloseableIterator it = new SimpleCloseableIterator(); assertThat(it.next()).isEqualTo(1); assertThat(it.next()).isEqualTo(2); try { it.next(); fail(); } catch (NoSuchElementException expected) { } }
public void ipCheck(EidSession session, String clientIp) { if (session.getClientIpAddress() != null && !session.getClientIpAddress().isEmpty()) { String[] clientIps = clientIp.split(", "); byte[] data = clientIps[0].concat(sourceIpSalt).getBytes(StandardCharsets.UTF_8); Stri...
@Test public void testIpCheckIncorrectIp() { setIpCheck(true); EidSession session = new EidSession(); // this ip is one = sign bigger session.setClientIpAddress("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); ClientException thrown = assertThrows(ClientException.class, () ...
public static Map<String, Object> merge(Map<String, Object> orig, Map<String, Object> update) { final Map<String, Object> merged = new HashMap<>(orig); update.forEach((k, v) -> { if (orig.get(k) instanceof EncryptedValue origValue && v instanceof EncryptedValue newValue) { me...
@Test void testMerge_keepValue() { final Map<String, Object> orig = Map.of( "unencrypted", "old unencrypted", "encrypted", encryptedValueService.encrypt("old encrypted") ); final Map<String, Object> update = Map.of( "encrypted", EncryptedValue....
public static List<URI> getPeerServerURIs(HelixManager helixManager, String tableNameWithType, String segmentName, String downloadScheme) { HelixAdmin helixAdmin = helixManager.getClusterManagmentTool(); String clusterName = helixManager.getClusterName(); List<URI> onlineServerURIs = new ArrayList<>()...
@Test public void testSegmentNotFound() { assertTrue(PeerServerSegmentFinder.getPeerServerURIs(_helixManager, REALTIME_TABLE_NAME, SEGMENT_2, CommonConstants.HTTP_PROTOCOL).isEmpty()); }
@Override public boolean isAutoTrackEnabled() { return false; }
@Test public void isAutoTrackEnabled() { List<SensorsDataAPI.AutoTrackEventType> typeList = new ArrayList<>(); typeList.add(SensorsDataAPI.AutoTrackEventType.APP_START); typeList.add(SensorsDataAPI.AutoTrackEventType.APP_END); mSensorsAPI.disableAutoTrack(typeList); Assert.as...
void changePopInvisibleTimeAsync(String topic, String consumerGroup, String extraInfo, long invisibleTime, AckCallback callback) throws MQClientException, RemotingException, InterruptedException, MQBrokerException { String[] extraInfoStrs = ExtraInfoUtil.split(extraInfo); String brokerName = Ext...
@Test public void testChangePopInvisibleTimeAsync() throws MQBrokerException, RemotingException, InterruptedException, MQClientException { AckCallback callback = mock(AckCallback.class); String extraInfo = createMessageExt().getProperty(MessageConst.PROPERTY_POP_CK); defaultMQPushConsumerImp...
@Override public List<ApplicationAttemptId> getAppsInQueue(String queueName) { FSQueue queue = queueMgr.getQueue(queueName); if (queue == null) { return null; } List<ApplicationAttemptId> apps = new ArrayList<ApplicationAttemptId>(); queue.collectSchedulerApplications(apps); return apps;...
@Test public void testGetAppsInQueue() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId appAttId1 = createSchedulingRequest(1024, 1, "queue1.subqueue1", "user1"); ApplicationAttemptId appAttId2 =...
@Override public int getLinkCount() { checkPermission(LINK_READ); return store.getLinkCount(); }
@Test public void updateLink() { addLink(DID1, P1, DID2, P2, DIRECT); addLink(DID2, P2, DID1, P1, INDIRECT); assertEquals("incorrect link count", 2, service.getLinkCount()); providerService.linkDetected(new DefaultLinkDescription(cp(DID2, P2), cp(DID1, P1), DIRECT)); validat...
@Override public Mono<SetProfileResponse> setProfile(final SetProfileRequest request) { validateRequest(request); return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice) .flatMap(authenticatedDevice -> Mono.zip( Mono.fromFuture(() -> accountsManager.getByAccountIdentifierA...
@Test void setProfile() throws InvalidInputException { final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize(); final byte[] validAboutEmoji = new byte[60]; final byte[] validAbout = new byte[540]; final byte[] validPaymentAddress = new by...
public static UPrimitiveTypeTree create(TypeTag tag) { return new AutoValue_UPrimitiveTypeTree(tag); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.INT), UPrimitiveTypeTree.INT) .addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.LONG), UPrimitiveTypeTree.LONG) .addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.DOUBLE), UPrimitiveTyp...
public Mono<CosmosContainerResponse> createContainer( final String containerId, final String containerPartitionKeyPath, final ThroughputProperties throughputProperties, final IndexingPolicy indexingPolicy) { CosmosDbUtils.validateIfParameterIsNotEmpty(containerId, PARAM_CONTAINER_ID); ...
@Test void testCreateContainer() { final CosmosAsyncDatabase database = mock(CosmosAsyncDatabase.class); final CosmosContainerResponse containerResponse = mock(CosmosContainerResponse.class); when(containerResponse.getProperties()).thenReturn(new CosmosContainerProperties("test-container", ...
@Override public String[] split(String text) { boundary.setText(text); List<String> words = new ArrayList<>(); int start = boundary.first(); int end = boundary.next(); while (end != BreakIterator.DONE) { String word = text.substring(start, end).trim(); ...
@Test public void testSplitContraction() { System.out.println("tokenize contraction"); String text = "Here are some examples of contractions: 'tis, " + "'twas, ain't, aren't, Can't, could've, couldn't, didn't, doesn't, " + "don't, hasn't, he'd, he'll, he's, how'd, how...
public Stream<Hit> stream() { if (nPostingLists == 0) { return Stream.empty(); } return StreamSupport.stream(new PredicateSpliterator(), false); }
@Test void requireThatSortingWorksForManyPostingLists() { PredicateSearch search = createPredicateSearch( new byte[]{1, 5, 2, 2}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x000100ff), entry(1, 0x000100ff)), ...
@Override public boolean isAuthenticationRequired(SubjectConnectionReference conn) { Subject subject = conn.getSubject(); if (subject.isAuthenticated()) { //already authenticated: return false; } //subject is not authenticated. Authentication is required by ...
@Test public void testIsAuthenticationRequiredWhenSystemConnectionAndSystemSubject() { Subject subject = new SubjectAdapter() { @Override public PrincipalCollection getPrincipals() { return new SimplePrincipalCollection("system", "iniRealm"); } };...
@Udf(description = "Converts a string representation of a date in the given format" + " into the TIMESTAMP value." + " Single quotes in the timestamp format can be escaped with ''," + " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.") public Timestamp parseTimestamp( @UdfParameter( descrip...
@Test public void shouldParseTimestamp() throws ParseException { // When: final Object result = udf.parseTimestamp("2021-12-01 12:10:11.123", "yyyy-MM-dd HH:mm:ss.SSS"); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); ...
public static boolean isSubdirectoryOf(File parent, File subdirectory) throws IOException { File parentFile = parent.getCanonicalFile(); File current = subdirectory.getCanonicalFile(); while (current != null) { if (current.equals(parentFile)) { return true; ...
@Test void shouldDetectSubfoldersWhenUsingRelativePaths() throws Exception { File parent = new File("/a/b"); assertThat(isSubdirectoryOf(parent, new File(parent, "../../.."))).isFalse(); }
public long getId(final WorkerNetAddress address) throws IOException { return retryRPC(() -> { GetWorkerIdPRequest request = GetWorkerIdPRequest.newBuilder().setWorkerNetAddress(GrpcUtils.toProto(address)).build(); return mClient.getWorkerId(request).getWorkerId(); }, LOG, "GetId", "addres...
@Test public void getId() throws Exception { WorkerNetAddress testExistsAddress = new WorkerNetAddress(); WorkerNetAddress testNonExistsAddress = new WorkerNetAddress(); testNonExistsAddress.setHost("1.2.3.4"); long workerId = 1L; Map<WorkerNetAddress, Long> workerIds = ImmutableMap.of(testExistsA...
public static Runnable catchingAndLoggingThrowables(Runnable runnable) { return new CatchingAndLoggingRunnable(runnable); }
@Test public void shouldCatchAndLogException() { Runnables.catchingAndLoggingThrowables(() -> { throw new RuntimeException(); }).run(); }
@Override public void run() { synchronized (this) { serverPushClient.writeAndFlush('\r'); serverPushClient.writeAndFlush('\n'); } serverPushClient.scheduleHeartbeat(); }
@Test public void run_reSchedulesHeartBeat() { underTest.run(); verify(serverPushClient, times(2)).writeAndFlush(anyChar()); verify(serverPushClient).scheduleHeartbeat(); }
@Override public void validate(final Analysis analysis) { failPersistentQueryOnWindowedTable(analysis); QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis); }
@Test public void shouldNotThrowOnPersistentPushQueryOnUnwindowedTable() { // Given: givenPersistentQuery(); givenSourceTable(); givenUnwindowedSource(); // When/Then(don't throw): validator.validate(analysis); }
public void addPermission(String role, String resource, String action) { if (!roleSet.contains(role)) { throw new IllegalArgumentException("role " + role + " not found!"); } permissionPersistService.addPermission(role, resource, action); }
@Test void addPermission() { try { nacosRoleService.addPermission("role-admin", "", "rw"); } catch (Exception e) { assertTrue(e.getMessage().contains("role role-admin not found!")); } }
@SuppressWarnings("unchecked") public E lookup(final int key) { @DoNotSub int size = this.size; final int[] keys = this.keys; final Object[] values = this.values; for (@DoNotSub int i = 0; i < size; i++) { if (key == keys[i]) { fin...
@Test void shouldReconstructItemsAfterEviction() { cache.lookup(1); final AutoCloseable second = cache.lookup(2); cache.lookup(3); cache.lookup(1); verify(mockCloser).accept(second); verifyOneConstructed(2); }
public static StackTraceElement[] extract(Throwable t, String fqnOfInvokingClass, final int maxDepth, List<String> frameworkPackageList) { if (t == null) { return null; } StackTraceElement[] steArray = t.getStackTrace(); StackTraceElement[] callerDataArray; ...
@Test public void testBasic() { Throwable t = new Throwable(); StackTraceElement[] steArray = t.getStackTrace(); StackTraceElement[] cda = CallerData.extract(t, CallerDataTest.class.getName(), 100, null); Arrays.stream(cda).forEach( ste -> System.out.println(ste)); assertNot...
@Override public void resolve(ConcurrentJobModificationException e) { final List<Job> concurrentUpdatedJobs = e.getConcurrentUpdatedJobs(); final List<ConcurrentJobModificationResolveResult> failedToResolve = concurrentUpdatedJobs .stream() .map(this::resolve) ...
@Test void concurrentStateChangeFromUnsupportedStateChangeIsNotAllowedAndThrowsException() { final Job job1 = aJobInProgress().build(); final Job job2 = aJobInProgress().build(); when(storageProvider.getJobById(job1.getId())).thenReturn(aCopyOf(job1).build()); when(storageProvider.g...
public synchronized void write(Mutation tableRecord) throws IllegalStateException { write(ImmutableList.of(tableRecord)); }
@Test public void testWriteMultipleRecordsShouldWorkWhenSpannerWriteSucceeds() throws ExecutionException, InterruptedException { // arrange prepareTable(); when(spanner.getDatabaseClient(any()).write(any())).thenReturn(Timestamp.now()); ImmutableList<Mutation> testMutations = ImmutableLi...
@Override public void validate(final Analysis analysis) { try { RULES.forEach(rule -> rule.check(analysis)); } catch (final KsqlException e) { throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e); } QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis...
@Test public void shouldThrowOnGroupBy() { // Given: when(analysis.getGroupBy()).thenReturn(Optional.of(new GroupBy( Optional.empty(), ImmutableList.of(AN_EXPRESSION) ))); // When: final Exception e = assertThrows( KsqlException.class, () -> validator.validate(anal...
@Override public PageResult<DictTypeDO> getDictTypePage(DictTypePageReqVO pageReqVO) { return dictTypeMapper.selectPage(pageReqVO); }
@Test public void testGetDictTypePage() { // mock 数据 DictTypeDO dbDictType = randomPojo(DictTypeDO.class, o -> { // 等会查询到 o.setName("yunai"); o.setType("芋艿"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCreateTime(buildTime(2021, 1, 15)); }...
@Deprecated public long searchOffset(final String addr, final String topic, final int queueId, final long timestamp, final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException { SearchOffsetRequestHeader requestHeader = new SearchOffsetRequestHeader(); ...
@Test public void testSearchOffset() throws Exception { doAnswer((Answer<RemotingCommand>) mock -> { RemotingCommand request = mock.getArgument(1); final RemotingCommand response = RemotingCommand.createResponseCommand(SearchOffsetResponseHeader.class); final SearchOffse...
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoun...
@Test public void shouldDelegateToHandlerForConstructors() throws Exception { Class<?> clazz = loadClass(AClassWithNoDefaultConstructor.class); Constructor<?> ctor = clazz.getDeclaredConstructor(String.class); assertThat(Modifier.isPublic(ctor.getModifiers())).isFalse(); ctor.setAccessible(true); ...
public ContainerBuildPlan toContainerBuildPlan() { return containerBuildPlanBuilder.build(); }
@Test public void testToContainerBuildPlan_default() throws InvalidImageReferenceException { ImageConfiguration imageConfiguration = ImageConfiguration.builder(ImageReference.parse("base/image")).build(); JibContainerBuilder containerBuilder = new JibContainerBuilder(imageConfiguration, spyBui...
@Override public int hashCode() { return hashCode; }
@Test void assertDifferentHashCode() { assertThat(new Grantee("name", "").hashCode(), not(new Grantee("name", "127.0.0.1").hashCode())); }
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema == null && value == null) { return null; } JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value); ...
@Test public void nullSchemaAndMapToJson() { // This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match // types to verify conversion still works. Map<String, Object> input = new HashMap<>(); input.put("key1", 12); input.put("k...
public static void validateValue(Schema schema, Object value) { validateValue(null, schema, value); }
@Test public void testValidateValueMismatchMapValue() { assertThrows(DataException.class, () -> ConnectSchema.validateValue(MAP_INT_STRING_SCHEMA, Collections.singletonMap(1, 2))); }
public void setHeader(Header header) { this.header = header; }
@Test void testSetHeader() { HttpRestResult<String> result = new HttpRestResult<>(); result.setData("test data"); Header header = Header.newInstance(); result.setHeader(header); assertEquals(header, result.getHeader()); assertEquals("test data", result.getData()); ...
public static <T, ComparatorT extends Comparator<T> & Serializable> Combine.Globally<T, List<T>> of(int count, ComparatorT compareFn) { return Combine.globally(new TopCombineFn<>(count, compareFn)); }
@Test public void testTopEmptyWithIncompatibleWindows() { p.enableAbandonedNodeEnforcement(false); Window<String> windowingFn = Window.into(FixedWindows.of(Duration.standardDays(10L))); PCollection<String> input = p.apply(Create.empty(StringUtf8Coder.of())).apply(windowingFn); expectedEx.expect(Ille...
public static Sensor getInvocationSensor( final Metrics metrics, final String sensorName, final String groupName, final String functionDescription ) { final Sensor sensor = metrics.sensor(sensorName); if (sensor.hasMetrics()) { return sensor; } final BiFunction<String, S...
@Test public void shouldRegisterCountMetric() { // Given: when(metrics.metricName(SENSOR_NAME + "-count", GROUP_NAME, description(COUNT_DESC))) .thenReturn(specificMetricName); // When: FunctionMetrics .getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME); // Then: ...
public static <T> T[] addAll(final T[] array1, @SuppressWarnings("unchecked") final T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); ...
@Test public void assertAddAll() { String[] array = new String[]{"1"}; Assert.isTrue(ArrayUtil.addAll(array, null).length == 1); Assert.isTrue(ArrayUtil.addAll(null, array).length == 1); Assert.isTrue(ArrayUtil.addAll(array, new String[]{"1"}).length == 2); }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatNullLiteral() { assertThat(ExpressionFormatter.formatExpression(new NullLiteral()), equalTo("null")); }
@Transactional public Spending updateSpending(Long spendingId, SpendingReq request) { Spending spending = spendingService.readSpending(spendingId).orElseThrow(() -> new SpendingErrorException(SpendingErrorCode.NOT_FOUND_SPENDING)); SpendingCustomCategory customCategory = (request.isCustomCategory()...
@DisplayName("커스텀 카테고리를 사용한 지출 내역으로 수정할 시, 커스텀 카테고리를 포함하는 지출내역으로 Spending 객체가 수정 된다.") @Test void testUpdateSpendingWithCustomCategory() { // given Long spendingId = 1L; given(spendingService.readSpending(spendingId)).willReturn(Optional.of(spending)); given(spendingCustomCategor...
@Udf public String uuid() { return java.util.UUID.randomUUID().toString(); }
@Test public void shouldHaveCorrectOutputFormat() { // aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee final String anUuid = udf.uuid(); assertThat(anUuid.length(), is(36)); assertThat(anUuid.charAt(8), is('-')); assertThat(anUuid.charAt(13), is('-')); assertThat(anUuid.charAt(18), is('-')); assertTh...