focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
void handleStatement(final QueuedCommand queuedCommand) { throwIfNotConfigured(); handleStatementWithTerminatedQueries( queuedCommand.getAndDeserializeCommand(commandDeserializer), queuedCommand.getAndDeserializeCommandId(), queuedCommand.getStatus(), Mode.EXECUTE, queue...
@Test(expected = IllegalStateException.class) public void shouldThrowOnHandleStatementIfNotConfigured() { // Given: statementExecutor = new InteractiveStatementExecutor( serviceContext, mockEngine, mockParser, mockQueryIdGenerator, commandDeserializer ); final M...
public boolean resetTaskOffset(String previousFailedTaskId) { final Task task = executionDAOFacade.getTaskById(previousFailedTaskId); final Workflow workflow = executionDAOFacade.getWorkflowById(task.getWorkflowInstanceId(), true); Optional<Task> currentTask = workflow.getTasks().stream() ...
@Test public void testResetOffsetNotFound() { String workflowId = "workflow-id"; String taskId = "task-id-1"; String taskId1 = "task-id-2"; Task maestroTask = new Task(); maestroTask.setTaskType(Constants.MAESTRO_TASK_NAME); maestroTask.setReferenceTaskName("maestroTask"); maestroTask.set...
PreparedStatement createPsForInsertConfigInfo(final String srcIp, final String srcUser, final ConfigInfo configInfo, Map<String, Object> configAdvanceInfo, Connection connection, ConfigInfoMapper configInfoMapper) throws SQLException { final String appNameTmp = StringUtils.defaultEmptyIf...
@Test void testCreatePsForInsertConfigInfo() throws SQLException { Map<String, Object> configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); configAdvanceInfo.put("desc", "desc11"); configAdvanceInfo.put("use", "use2233"); configAdva...
public static StringBuilder createBuilder(CharSequence... charSequences) { StringBuilder builder = new StringBuilder(); if (charSequences == null || charSequences.length == 0) { return builder; } for (CharSequence sequence : charSequences) { builder.append(sequenc...
@Test public void createBuilder() { StringBuilder s1 = StringUtil.createBuilder(null); Assert.assertEquals("", s1.toString()); StringBuilder s2 = StringUtil.createBuilder("H", "ippo", "4j"); Assert.assertEquals("Hippo4j", s2.toString()); }
@Deprecated public boolean cancel(Timer timer) { assert (timer.parent == this); return timer.cancel(); }
@Test public void testCancel() { long fullTimeout = 100; Timers.Timer timer = timers.add(fullTimeout, handler, invoked); // cancel timer long timeout = timers.timeout(); boolean ret = timer.cancel(); assertThat(ret, is(true)); ZMQ.msleep(timeout * 2); ...
public static TimeLock ofTimestamp(Instant time) { long secs = time.getEpochSecond(); if (secs < THRESHOLD) throw new IllegalArgumentException("timestamp too low: " + secs); return new TimeLock(secs); }
@Test(expected = IllegalArgumentException.class) public void ofTimestamp_negative() { LockTime.ofTimestamp(Instant.EPOCH.minusSeconds(1)); }
@Override public KeyValueIterator<Windowed<K>, V> fetch(final K key) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType); for (final ReadOnlySessionStore<K, V> store : stores) { tr...
@Test public void shouldThrowNullPointerExceptionIfFetchingNullKey() { assertThrows(NullPointerException.class, () -> sessionStore.fetch(null)); }
@Override public LinkEvent removeLink(ConnectPoint src, ConnectPoint dst) { final LinkKey linkKey = LinkKey.linkKey(src, dst); ProviderId primaryProviderId = getBaseProviderId(linkKey); // Stop if there is no base provider. if (primaryProviderId == null) { return null; ...
@Test public final void testRemoveLink() { final ConnectPoint d1P1 = new ConnectPoint(DID1, P1); final ConnectPoint d2P2 = new ConnectPoint(DID2, P2); LinkKey linkId1 = LinkKey.linkKey(d1P1, d2P2); LinkKey linkId2 = LinkKey.linkKey(d2P2, d1P1); putLink(linkId1, DIRECT, A1); ...
@Override public OAuth2AccessTokenDO grantRefreshToken(String refreshToken, String clientId) { return oauth2TokenService.refreshAccessToken(refreshToken, clientId); }
@Test public void testGrantRefreshToken() { // 准备参数 String refreshToken = randomString(); String clientId = randomString(); // mock 方法 OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class); when(oauth2TokenService.refreshAccessToken(eq(refreshToken...
public List<InterpreterResultMessage> message() { return msg; }
@Test void testComplexMagicData() { InterpreterResult result = null; result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before\n%table col1\tcol2\naaa\t123\n"); assertEquals("some text before\n", result.message().get(0).getData(), "text before %table"); assertEquals("c...
public DateCache() { cache = new HashMap<String, Date>(); }
@SuppressWarnings( "deprecation" ) @Test public void testDateCache() { DateCache cache = new DateCache(); cache.populate( "yyyy-MM-dd", 2016, 2016 ); assertEquals( 366, cache.getSize() ); // Leap year assertEquals( Calendar.FEBRUARY, cache.lookupDate( "2016-02-29" ).getMonth() ); assertEquals( 2...
public static void initRequestEntity(HttpRequestBase requestBase, Object body, Header header) throws Exception { if (body == null) { return; } if (requestBase instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) reques...
@Test void testInitRequestEntity3() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); Header header = Header.newInstance(); header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html"); HttpUtils.initRequestEntity(http...
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds); intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub); for (String feature : FEATURES_IN_ORDER) { ...
@Test void testApplyTransforms_blws() { // given List<Integer> glyphsAfterGsub = Arrays.asList(278,76,333,337,276); // when List<Integer> result = gsubWorkerForGujarati.applyTransforms(getGlyphIds("હૃટ્રુણુરુ")); // then assertEquals(glyphsAfterGsub, result); ...
@Override public Integer doCall() throws Exception { List<Row> rows = new ArrayList<>(); JsonObject plugins = loadConfig().getMap("plugins"); plugins.forEach((key, value) -> { JsonObject details = (JsonObject) value; String name = details.getStringOrDefault("name", ...
@Test public void shouldGetEmptyPlugins() throws Exception { PluginGet command = new PluginGet(new CamelJBangMain().withPrinter(printer)); command.doCall(); Assertions.assertEquals("", printer.getOutput()); }
public void addCookie(JDiscCookieWrapper cookie) { if (cookie != null) { List<Cookie> cookies = new ArrayList<>(); // Get current set of cookies first List<Cookie> c = getCookies(); if (c != null && !c.isEmpty()) { cookies.addAll(c); } ...
@Test void testAddCookie() { URI uri = URI.create("http://example.yahoo.com/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); DiscFilterRequest request = new DiscFilterRequest(httpReq); request.addCookie(JDiscCookieWrapper.wrap(new C...
public UiTopoLayout geomap(String geomap) { if (sprites != null) { throw new IllegalArgumentException(E_SPRITES_SET); } this.geomap = geomap; return this; }
@Test public void setGeomap() { mkRootLayout(); assertEquals("geo to start", null, layout.geomap()); layout.geomap(GEOMAP); assertEquals("wrong geo", GEOMAP, layout.geomap()); }
@Override @MethodNotAvailable public CompletionStage<Void> setAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testSetAsync() { adapter.setAsync(42, "value"); }
public static AggregationFunctionColumnPair resolveToStoredType(AggregationFunctionColumnPair functionColumnPair) { AggregationFunctionType storedType = getStoredType(functionColumnPair.getFunctionType()); return new AggregationFunctionColumnPair(storedType, functionColumnPair.getColumn()); }
@Test public void testResolveToStoredType() { assertEquals(AggregationFunctionColumnPair.fromColumnName("distinctCountThetaSketch__dimX"), AggregationFunctionColumnPair.resolveToStoredType( AggregationFunctionColumnPair.fromColumnName("distinctCountRawThetaSketch__dimX"))); assertEquals(Ag...
@PublicAPI(usage = ACCESS) public JavaClasses importUrl(URL url) { return importUrls(singletonList(url)); }
@Test public void imports_subclass_in_class_hierarchy_correctly() { JavaClass subclass = new ClassFileImporter().importUrl(getClass().getResource("testexamples/classhierarchyimport")).get(Subclass.class); assertThat(subclass.getConstructors()).hasSize(3); assertThat(subclass.getFields()).ha...
public static <T, R> OneInputTransformation<T, R> getOneInputTransformation( String operatorName, AbstractDataStream<T> inputStream, TypeInformation<R> outTypeInformation, OneInputStreamOperator<T, R> operator) { // read the output type of the input Transform to c...
@Test void testGetOneInputTransformation() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); ProcessOperator<Integer, Long> operator = new ProcessOperator<>(new StreamTestUtils.NoOpOneInputStreamProcessFunction()); OneInputTransformation<Integer, Lon...
public static <T> Partition<T> of( int numPartitions, PartitionWithSideInputsFn<? super T> partitionFn, Requirements requirements) { Contextful ctfFn = Contextful.fn( (T element, Contextful.Fn.Context c) -> partitionFn.partitionFor(element, numPartitions, c), ...
@Test public void testDisplayDataOfSideViewFunction() { Partition<?> partition = Partition.of(123, new IdentitySideViewFn(), Requirements.empty()); DisplayData displayData = DisplayData.from(partition); assertThat(displayData, hasDisplayItem("numPartitions", 123)); assertThat(displayData, hasDisplayI...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchResponseMetricsWithOnePartitionAtTheWrongOffset() { buildFetcher(); assignFromUser(mkSet(tp0, tp1)); subscriptions.seek(tp0, 0); subscriptions.seek(tp1, 0); Map<MetricName, KafkaMetric> allMetrics = metrics.metrics(); KafkaMetric fetchSize...
public void run() { try { targetFile = KettleVFS.getFileObject( targetPath ); if ( targetFile.exists() ) { if ( !targetFile.delete() ) { throw new ReportProcessingException( messages.getErrorString( "ReportExportTask.ERROR_0001_TARGET_EXISTS" ) ); //$NON-NLS-1$ } } ...
@Test public void testExportReportWithUnsupportedLocale() { when( masterReport.getConfiguration() ).thenReturn( mock( Configuration.class ) ); when( masterReport.getResourceManager() ).thenReturn( new ResourceManager() ); when( swingGuiContext.getLocale() ).thenReturn( Locale.UK ); when( swingGuiCont...
@NonNull @Override public IdpListJWS fetchIdpList(URI idpListUrl) { return idpListCache.computeIfAbsent( idpListUrl.toString(), k -> delegate.fetchIdpList(idpListUrl)); }
@Test void fetchIdpList() { var uri = URI.create("https://example.com/idpList"); var expected = new IdpListJWS(null, null); when(delegate.fetchIdpList(uri)).thenReturn(expected); // when var got = sut.fetchIdpList(uri); // then verify(delegate).fetchIdpList(uri); assertEquals(expect...
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) { List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext() ? createShardingConditionsWithInsertValues(sqlStatementContext, params) ...
@Test void assertCreateShardingConditionsInsertStatementWithGeneratedKeyContextUsingCommonExpressionSegmentEmpty() { when(insertStatementContext.getInsertValueContexts()).thenReturn(Collections.singletonList(createInsertValueContextAsCommonExpressionSegmentEmptyText())); when(insertStatementContext....
@Override public void initialize(@Nullable Configuration configuration, Properties serDeProperties) throws SerDeException { // HiveIcebergSerDe.initialize is called multiple places in Hive code: // - When we are trying to create a table - HiveDDL data is stored at the serDeProperties, but // no Iceb...
@Test public void testInitialize() throws IOException, SerDeException { File location = tmp.toFile(); assertThat(location.delete()).isTrue(); Configuration conf = new Configuration(); Properties properties = new Properties(); properties.setProperty("location", location.toString()); propertie...
public static ConfigMap createConfigMap( String name, String namespace, Labels labels, OwnerReference ownerReference, Map<String, String> data ) { return new ConfigMapBuilder() .withNewMetadata() .withName(name) ...
@Test public void testConfigMapCreation() { ConfigMap cm = ConfigMapUtils.createConfigMap(NAME, NAMESPACE, LABELS, OWNER_REFERENCE, Map.of("key1", "value1", "key2", "value2")); assertThat(cm.getMetadata().getName(), is(NAME)); assertThat(cm.getMetadata().getNamespace(), is(NAMESPACE)); ...
public static int findEndOfMethodArgsIndex(CharSequence string, int startOfMethodArgsIndex) { boolean isDoubleQuoted = false; boolean isSingleQuoted = false; int nestingLevel = 0; for (int charIndex = startOfMethodArgsIndex; charIndex < string.length(); charIndex++) { boolean...
@Test public void testFindEndOfMethodArgsIndex() { findEndOfMethodArgsIndexAndAssertItEqualsToExpected("setId(\"myId\")", 12); findEndOfMethodArgsIndexAndAssertItEqualsToExpected("setId(\"myId\").call()", 12); findEndOfMethodArgsIndexAndAssertItEqualsToExpected("setId('myId')", 12); ...
public List<String> build() { if (columnDefs.isEmpty()) { throw new IllegalStateException("No column has been defined"); } switch (dialect.getId()) { case PostgreSql.ID: return createPostgresQuery(); case Oracle.ID: return createOracleQuery(); default: return ...
@Test public void update_not_nullable_column_on_oracle() { assertThat(createNotNullableBuilder(new Oracle()).build()) .containsOnly("ALTER TABLE issues MODIFY (name VARCHAR2 (10 CHAR) NOT NULL)"); }
@Override public boolean next() throws SQLException { return mergeResultSet.next(); }
@Test void assertNext() throws SQLException { when(mergeResultSet.next()).thenReturn(true); assertTrue(shardingSphereResultSet.next()); }
@PublicAPI(usage = ACCESS) public JavaClasses importClasses(Class<?>... classes) { return importClasses(Arrays.asList(classes)); }
@Test public void imports_enclosing_method_of_anonymous_class() throws ClassNotFoundException { @SuppressWarnings("unused") class ClassCreatingAnonymousClassInMethod { void someMethod() { new Serializable() { }; } } String anony...
public static void cleanDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); Path path = directory.toPath(); if (!path.toFile().exists()) { return; } cleanDirectoryImpl(path); }
@Test public void cleanDirectory_throws_NPE_if_file_is_null() throws IOException { assertThatThrownBy(() -> FileUtils.cleanDirectory(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Directory can not be null"); }
@Override public int hashCode() { int result = (materialType != null ? materialType.hashCode() : 0); result = 31 * result + (pipelineName != null ? pipelineName.hashCode() : 0); result = 31 * result + (stageName != null ? stageName.hashCode() : 0); return result; }
@Test void hashCodeImplementation() throws Exception { DependencyMaterial one = new DependencyMaterial(new CaseInsensitiveString("pipelineName"), new CaseInsensitiveString("stage")); DependencyMaterial two = new DependencyMaterial(new CaseInsensitiveString("pipelineName"), new CaseInsensitiveString(...
@Override public final void initialize(Bootstrap<?> bootstrap) { bootstrap.getObjectMapper().registerModule(createHibernate5Module()); }
@Test void addsHibernateSupportToJackson() throws Exception { final ObjectMapper objectMapperFactory = mock(ObjectMapper.class); final Bootstrap<?> bootstrap = mock(Bootstrap.class); when(bootstrap.getObjectMapper()).thenReturn(objectMapperFactory); bundle.initialize(bootstrap); ...
public synchronized void deletePartitionSchema( PartitionSchema removed ) { synchronizeTransformations( true, transMeta -> transMeta.getPartitionSchemas().remove( removed ) ); }
@Test public void synchronizePartitionSchemasDeleteFromRepository() throws Exception { try { spoon.rep = repository; when( spoon.getRepository() ).thenReturn( repository ); final String objectId = "object-id"; final String partitionName = "partsch"; TransMeta trans1 = createTransMe...
MatchResult matchPluginTemplate(String ownerTemplate, String template) { boolean matches = false; String pluginName = null; String templateName = template; String ownerTemplateName = ownerTemplate; if (StringUtils.isNotBlank(ownerTemplate)) { Matcher ownerTemplateMatc...
@Test void matchPluginTemplateWhenTemplateMatch() { var result = templateResolver.matchPluginTemplate("doc", "plugin:fake-plugin:modules/layout"); assertThat(result.matches()).isTrue(); assertThat(result.pluginName()).isEqualTo("fake-plugin"); assertThat(result.templateNa...
@Override public String toString() { return datum.toString(); }
@Test void testToString() { String datum = "my string"; AvroWrapper<CharSequence> wrapper = new AvroWrapper<>(datum); assertEquals(datum, wrapper.toString()); }
@Override public FlumeConfiguration getFlumeConfiguration() { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String resolverClassName = System.getProperty("propertiesImplementation", DEFAULT_PROPERTIES_IMPLEMENTATION...
@Test public void testPropertyRead() { FlumeConfiguration configuration = provider.getFlumeConfiguration(); assertNotNull(configuration); /* * Test the known errors in the file */ List<String> expected = Lists.newArrayList(); expected.add("host5 CONFIG_ERROR"); ...
public String getPomUrl() { return pomUrl; }
@Test public void getPomUrl() { // Given final MavenArtifact mavenArtifact = new MavenArtifact("com.google.code.gson", "gson", "2.1", "https://artifactory.techno.ingenico.com/artifactory/jcenter-cache/com/google/code/gson/gson/2.1/gson-2.1.jar", MavenArtifact.derivePomUrl("gson", "2....
@Override public void loginSuccess(HttpRequest request, @Nullable String login, Source source) { checkRequest(request); requireNonNull(source, "source can't be null"); LOGGER.atDebug().setMessage("login success [method|{}][provider|{}|{}][IP|{}|{}][login|{}]") .addArgument(source::getMethod) ....
@Test public void login_success_message_is_sanitized() { logTester.setLevel(Level.DEBUG); underTest.loginSuccess(mockRequest("1.2.3.4"), "login with \n malicious line \r return", Source.sso()); assertThat(logTester.logs()).isNotEmpty() .contains("login success [method|SSO][provider|SSO|sso][IP|1.2...
public static String signWithHmacSha1Encrypt(String encryptText, String encryptKey) { try { byte[] data = encryptKey.getBytes(Constants.ENCODE); // Construct a key according to the given byte array, and the second parameter specifies the name of a key algorithm SecretKey secr...
@Test void testSignWithHmacSha1EncryptWithException() { assertThrows(Exception.class, () -> { SpasAdapter.signWithHmacSha1Encrypt(null, "123"); }); }
private Expect(ExpectationGatherer gatherer) { super(FailureMetadata.forFailureStrategy(gatherer)); this.gatherer = checkNotNull(gatherer); }
@Test public void expectFailWithExceptionBeforeExpectFailures() { thrown.expect(IllegalStateException.class); thrown.expectMessage("testing"); throwException(); expect.withMessage("x").fail(); expect.withMessage("y").fail(); }
protected String toString(Subject subject) { PrincipalCollection pc = subject.getPrincipals(); if (pc != null && !pc.isEmpty()) { return "[" + pc.toString() + "] "; } return ""; }
@Test public void testSubjectToString() { Subject subject = new PermsSubject() { @Override public PrincipalCollection getPrincipals() { return null; } }; String string = filter.toString(subject); assertEquals("", string); }
public static boolean hasChinese(CharSequence value) { return ReUtil.contains(ReUtil.RE_CHINESES, value); }
@Test public void hasChineseTest() { assertTrue(Validator.hasChinese("黄单桑米")); assertTrue(Validator.hasChinese("Kn 四兄弟")); assertTrue(Validator.hasChinese("\uD840\uDDA3")); assertFalse(Validator.hasChinese("Abc")); }
@Override public void accept(TimerEvent timerEvent) { logMessageConsumer.accept(buildLogMessage(timerEvent)); }
@Test public void testAccept() { TimerEventHandler timerEventHandler = new TimerEventHandler(logMessageQueue::add); timerEventHandler.accept( new TimerEvent(State.START, ROOT_TIMER, Duration.ZERO, Duration.ZERO, "description")); timerEventHandler.accept( new TimerEvent(State.LAP, ROOT_TIM...
private InterpreterResult renderTable(List<String> cols, List<List<String>> lines) { LOGGER.info("Executing renderTable method"); StringBuilder msg = null; if (cols.isEmpty()) { msg = new StringBuilder(); } else { msg = new StringBuilder(TABLE); msg.append(NEW_LINE); msg.append(S...
@Test void testRenderTable() { interpreter.open(); InterpreterResult result = interpreter.interpret("MATCH (n:Person) " + "WHERE n.name IN ['name1', 'name2', 'name3'] " + "RETURN n.name AS name, n.age AS age, " + "n.address AS address, n.birth AS birth", context); asser...
@Override public boolean verify(final Host host, final PublicKey key) throws BackgroundException { String lookup = preferences.getProperty(this.toFormat(host, key)); if(StringUtils.isEmpty(lookup)) { // Backward compatiblity to find keys with no port number saved lookup = pre...
@Test public void testVerifyDenyServerHostKey() throws Exception { PreferencesHostKeyVerifier v = new PreferencesHostKeyVerifier() { @Override public boolean isChangedKeyAccepted(Host hostname, PublicKey key) { return false; } @Override ...
public static Collection<WhereSegment> getJoinWhereSegments(final SelectStatement selectStatement) { return selectStatement.getFrom().map(WhereExtractUtils::getJoinWhereSegments).orElseGet(Collections::emptyList); }
@Test void assertGetJoinWhereSegmentsWithEmptySelectStatement() { assertTrue(WhereExtractUtils.getJoinWhereSegments(mock(SelectStatement.class)).isEmpty()); }
@Override @Nullable public short[] readShortArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { short[] values = new short[len]; for (int i = 0; i < len; i++) { values...
@Test public void testReadShortArray() throws Exception { byte[] bytesBE = {0, 0, 0, 0, 0, 0, 0, 1, 0, 1, -1, -1, -1, -1}; byte[] bytesLE = {0, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, -1, -1, -1}; in.init((byteOrder == BIG_ENDIAN ? bytesBE : bytesLE), 0); in.position(bytesLE.length - 4); ...
public static void addRumHit(HttpServletRequest httpRequest, Counter httpCounter) { final String requestName = httpRequest.getParameter("requestName"); if (requestName == null) { return; } try { final long serverTime = Long.parseLong(httpRequest.getParameter("serverTime")); final long timeToFirstByte =...
@Test public void testAddRumHit() { final Counter httpCounter = new Counter(Counter.HTTP_COUNTER_NAME, "dbweb.png"); // test null requestName addRumHit(httpCounter, null, null, null, null, null); final String requestName = "test"; // test non-parseable values addRumHit(httpCounter, requestName, null, null...
public static Read<String> readStrings() { return Read.newBuilder( (PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8)) .setCoder(StringUtf8Coder.of()) .build(); }
@Test public void testTopicValidationTooLong() throws Exception { thrown.expect(IllegalArgumentException.class); PubsubIO.readStrings() .fromTopic( new StringBuilder() .append("projects/my-project/topics/A-really-long-one-") .append( "111...
@Override public boolean test(Pair<Point, Point> pair) { if (timeDeltaIsSmall(pair.first().time(), pair.second().time())) { return distIsSmall(pair); } else { /* * reject points with large time deltas because we don't want to rely on a numerically *...
@Test public void testCase4() { DistanceFilter filter = newTestFilter(); LatLong position1 = new LatLong(0.0, 0.0); double notTooFarInNm = MAX_DISTANCE_IN_FEET * 0.5 / Spherical.feetPerNM(); Point p1 = new PointBuilder() .latLong(position1) .time(Instant.EP...
public static DataSchema buildSchemaByProjection(DataSchema schema, DataMap maskMap) { return buildSchemaByProjection(schema, maskMap, Collections.emptyList()); }
@Test public void testBuildSchemaByEmptyProjection() { DataSchema schema = DataTemplateUtil.getSchema(RecordTemplateWithPrimitiveKey.class); DataMap projectionMask = buildProjectionMaskDataMap(); try { buildSchemaByProjection(schema, projectionMask); } catch (IllegalArgumentException ...
@Override public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { final CopyFileRequest copy = new CopyFileRequest() .name(target.getName()) ...
@Test public void testCopyServerSideToExistingFile() throws Exception { final StoregateIdProvider fileid = new StoregateIdProvider(session); final Path top = new StoregateDirectoryFeature(session, fileid).mkdir(new Path( String.format("/My files/%s", new AlphanumericRandomStringService()...
@Override public V takeLastAndOfferFirstTo(String queueName) throws InterruptedException { return commandExecutor.getInterrupted(takeLastAndOfferFirstToAsync(queueName)); }
@Test public void testTakeLastAndOfferFirstTo() throws InterruptedException { final RBlockingQueue<Integer> queue1 = redisson.getBlockingQueue("{queue}1"); Executors.newSingleThreadScheduledExecutor().schedule(() -> { try { queue1.put(3); } catch (InterruptedE...
@Override public void validateDictDataList(String dictType, Collection<String> values) { if (CollUtil.isEmpty(values)) { return; } Map<String, DictDataDO> dictDataMap = CollectionUtils.convertMap( dictDataMapper.selectByDictTypeAndValues(dictType, values), DictDat...
@Test public void testValidateDictDataList_notFound() { // 准备参数 String dictType = randomString(); List<String> values = singletonList(randomString()); // 调用, 并断言异常 assertServiceException(() -> dictDataService.validateDictDataList(dictType, values), DICT_DATA_NOT_EXISTS); ...
public String process(final Expression expression) { return formatExpression(expression); }
@Test public void shouldGenerateCorrectCodeForDateDateLT() { // Given: final ComparisonExpression compExp = new ComparisonExpression( Type.LESS_THAN, DATECOL, DATECOL ); // When: final String java = sqlToJavaVisitor.process(compExp); // Then: assertThat(java, cont...
public ControllerResult<ElectMasterResponseHeader> electMaster(final ElectMasterRequestHeader request, final ElectPolicy electPolicy) { final String brokerName = request.getBrokerName(); final Long brokerId = request.getBrokerId(); final ControllerResult<ElectMasterResponseHeader> result...
@Test public void testElectMaster() { mockMetaData(); final ElectMasterRequestHeader request = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME); final ControllerResult<ElectMasterResponseHeader> cResult = this.replicasInfoManager.electMaster(request, new DefaultE...
public AccessPrivilege getAccessPrivilege(InetAddress addr) { return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName()); }
@Test public void testRegexHostRW() { NfsExports matcher = new NfsExports(CacheSize, ExpirationPeriod, "[a-z]+.b.com rw"); Assert.assertEquals(AccessPrivilege.READ_WRITE, matcher.getAccessPrivilege(address1, hostname1)); // address1 will hit the cache Assert.assertEquals(AccessPrivileg...
@Override public String getMethod() { return PATH; }
@Test public void testGetChatMenuButtonAsDefault() { SetChatMenuButton setChatMenuButton = SetChatMenuButton .builder() .menuButton(MenuButtonDefault.builder().build()) .build(); assertEquals("setChatMenuButton", setChatMenuButton.getMethod()); ...
@Override public boolean setAlertFilter(String severity) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId...
@Test public void testValidSetAlertFilter() throws Exception { String target; boolean result; for (int i = ZERO; i < VALID_SET_TCS.length; i++) { target = VALID_SET_TCS[i]; currentKey = i; result = voltConfig.setAlertFilter(target); assertTrue...
@VisibleForTesting public String getLullMessage(Thread trackedThread, Duration millis) { // TODO(ajamato): Share getLullMessage code with DataflowExecutionState. String userStepName = this.labelsMetadata.getOrDefault(MonitoringInfoConstants.Labels.PTRANSFORM, null); StringBuilder message = new Str...
@Test public void testGetLullReturnsARelevantMessageWithStepName() { HashMap<String, String> labelsMetadata = new HashMap<String, String>(); labelsMetadata.put(MonitoringInfoConstants.Labels.PTRANSFORM, "myPTransform"); SimpleExecutionState testObject = new SimpleExecutionState("myState", null, labelsMeta...
public static Map.Entry<String, String> getRegressionTableBuilder(final RegressionTable regressionTable, final RegressionCompilationDTO compilationDTO) { logger.trace("getRegressionTableBuilder {}", regressionTable); String className ...
@Test void getRegressionTableBuilder() { regressionTable = getRegressionTable(3.5, "professional"); RegressionModel regressionModel = new RegressionModel(); regressionModel.setNormalizationMethod(RegressionModel.NormalizationMethod.CAUCHIT); regressionModel.addRegressionTables(regres...
public static String format(String source) { return new FormatProcess(source).perform().trim(); }
@Test @Disabled public void testKeyword() { final String sql = "select * from `order`"; final String format = SqlFormatter.format(sql); System.out.println(format); }
@Override public void handle(ContainersLauncherEvent event) { // TODO: ContainersLauncher launches containers one by one!! Container container = event.getContainer(); ContainerId containerId = container.getContainerId(); switch (event.getType()) { case LAUNCH_CONTAINER: Application app =...
@Test public void testSignalContainerEvent() throws IllegalArgumentException, IllegalAccessException, IOException { SignalContainersLauncherEvent dummyEvent = mock(SignalContainersLauncherEvent.class); when(dummyEvent.getContainer()).thenReturn(container); when(container.getContainerId()).t...
public Predicate convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testAnd() { BinaryPredicateOperator op1 = new BinaryPredicateOperator( BinaryType.GT, F0, ConstantOperator.createInt(2)); BinaryPredicateOperator op2 = new BinaryPredicateOperator( BinaryType.LT, F0, ConstantOperator.createInt(5)); ScalarOper...
public static Iterator<Row> computeUpdates( Iterator<Row> rowIterator, StructType rowType, String[] identifierFields) { Iterator<Row> carryoverRemoveIterator = removeCarryovers(rowIterator, rowType); ChangelogIterator changelogIterator = new ComputeUpdateIterator(carryoverRemoveIterator, rowType, ...
@Test public void testRowsWithNullValue() { final List<Row> rowsWithNull = Lists.newArrayList( new GenericRowWithSchema(new Object[] {2, null, null, DELETE, 0, 0}, null), new GenericRowWithSchema(new Object[] {3, null, null, INSERT, 0, 0}, null), new GenericRowWithSchem...
@Override public int countListeners() { return subscribeService.countListeners(channelName); }
@Test public void testCountListeners() { RTopic topic1 = redisson.getTopic("topic", LongCodec.INSTANCE); assertThat(topic1.countListeners()).isZero(); int id = topic1.addListener(Long.class, (channel, msg) -> { }); assertThat(topic1.countListeners()).isOne(); RTopic ...
@Override public void close() throws IOException { lock.lock(); try { if (closed) return; if (LOG.isDebugEnabled()) { LOG.debug(this + ": closing"); } closed = true; } finally { lock.unlock(); } // Close notificationSockets[0], so that notificationSockets[1] g...
@Test(timeout=60000) public void testInterruption() throws Exception { final DomainSocketWatcher watcher = newDomainSocketWatcher(10); watcher.watcherThread.interrupt(); Uninterruptibles.joinUninterruptibly(watcher.watcherThread); watcher.close(); }
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException { readData( stepnode, databases ); }
@Test public void testLoadXml() throws Exception { TableOutputMeta tableOutputMeta = new TableOutputMeta(); tableOutputMeta.loadXML( getTestNode(), databases, metaStore ); assertEquals( "1000", tableOutputMeta.getCommitSize() ); assertEquals( null, tableOutputMeta.getGeneratedKeyField() ); assert...
@Override public boolean retainAll(Collection<?> c) { boolean changed = false; for (byte[] item : items) { E deserialized = serializer.decode(item); if (!c.contains(deserialized)) { changed = items.remove(item) || changed; } } retur...
@Test public void testRetainAll() throws Exception { //Test ability to generate the intersection set Set<Integer> retainSet = Sets.newHashSet(); fillSet(10, set); assertTrue("The set should have changed.", set.retainAll(retainSet)); assertTrue("The set should have been emptie...
public static AliyunSlsLogCollectClient getAliyunSlsLogCollectClient() { return ALIYUN_SLS_LOG_COLLECT_CLIENT; }
@Test public void testGetAliyunSlsLogCollectClient() { Assertions.assertEquals(LoggingAliyunSlsPluginDataHandler.getAliyunSlsLogCollectClient().getClass(), AliyunSlsLogCollectClient.class); }
public static String wrapWithMarkdownClassDiv(String html) { return new StringBuilder() .append("<div class=\"markdown-body\">\n") .append(html) .append("\n</div>") .toString(); }
@Test void testOrderedList() { String input = new StringBuilder() .append("1. First ordered list item\n") .append("2. Another item") .toString(); String expected = new StringBuilder() .append("<ol>\n") .append("<li>First ordered list...
public static StringSetResult empty() { return EmptyStringSetResult.INSTANCE; }
@Test public void empty() { // Test empty returns an immutable set StringSetResult empptyStringSetResult = StringSetResult.empty(); assertTrue(empptyStringSetResult.getStringSet().isEmpty()); assertThrows( UnsupportedOperationException.class, () -> empptyStringSetResult.getStringSet()....
@Override public boolean available(String pluginName) { if (StringUtils.isBlank(pluginName)) { return false; } PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginName); if (pluginWrapper == null) { return false; } return PluginState.ST...
@Test void available() { assertThat(pluginFinder.available(null)).isFalse(); boolean available = pluginFinder.available("fake-plugin"); assertThat(available).isFalse(); PluginWrapper mockPluginWrapper = Mockito.mock(PluginWrapper.class); when(haloPluginManager.getPlugin(eq(...
@Override public void open(ExecutionContext ctx) throws Exception { super.open(ctx); equaliser = genRecordEqualiser.newInstance(ctx.getRuntimeContext().getUserCodeClassLoader()); }
@Test public void testWithoutGenerateUpdateBeforeAndInsert() throws Exception { ProcTimeMiniBatchDeduplicateKeepLastRowFunction func = createFunction(false, false, minTime.toMilliseconds()); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(func); ...
@Override public ClusterMetricsInfo getClusterMetricsInfo() { ClusterMetricsInfo metrics = new ClusterMetricsInfo(); Collection<SubClusterInfo> subClusterInfos = federationFacade.getActiveSubClusters(); Stream<ClusterMetricsInfo> clusterMetricsInfoStream = subClusterInfos.parallelStream() .map(s...
@Test public void testGetClusterMetrics() { ClusterMetricsInfo responseGet = interceptor.getClusterMetricsInfo(); Assert.assertNotNull(responseGet); int expectedAppSubmitted = 0; for (int i = 0; i < NUM_SUBCLUSTER; i++) { expectedAppSubmitted += i; } Assert.assertEquals(expectedAppSubm...
@Override public CompletableFuture<TopicList> queryTopicsByConsumer(String address, QueryTopicsByConsumerRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<TopicList> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestC...
@Test public void assertQueryTopicsByConsumerWithError() { setResponseError(); QueryTopicsByConsumerRequestHeader requestHeader = mock(QueryTopicsByConsumerRequestHeader.class); CompletableFuture<TopicList> actual = mqClientAdminImpl.queryTopicsByConsumer(defaultBrokerAddr, requestHeader, de...
public T orElseThrow() { return orElseThrow(NoSuchElementException::new, "No value present"); }
@Test public void orElseThrowTest() { assertThrows(NoSuchElementException.class, () -> { // 获取一个不可能为空的值,否则抛出NoSuchElementException异常 Object obj = Opt.ofNullable(null).orElseThrow(); assertNull(obj); }); }
public ConfigPayloadBuilder build(Element configE) { parseConfigName(configE); ConfigPayloadBuilder payloadBuilder = new ConfigPayloadBuilder(configDefinition); for (Element child : XML.getChildren(configE)) { parseElement(child, payloadBuilder, null); } return paylo...
@Test void require_that_exceptions_are_issued() throws FileNotFoundException { assertThrows(IllegalArgumentException.class, () -> { Element configRoot = getDocument( "<config name=\"test.simpletypes\">" + "<longval>invalid</longval>" + ...
public static boolean webSocketHostPathMatches(String hostPath, String targetPath) { boolean exactPathMatch = true; if (ObjectHelper.isEmpty(hostPath) || ObjectHelper.isEmpty(targetPath)) { // This scenario should not really be possible as the input args come from the vertx-websocket consum...
@Test void webSocketHostExactPathNotEnoughElementsNotMatches() { String hostPath = "/foo/bar/cheese/wine"; String targetPath = "/foo/bar"; assertFalse(VertxWebsocketHelper.webSocketHostPathMatches(hostPath, targetPath)); }
public int[] intersection(SparseVector other) { List<Integer> diffIndicesList = new ArrayList<>(); Iterator<VectorTuple> itr = iterator(); Iterator<VectorTuple> otherItr = other.iterator(); if (itr.hasNext() && otherItr.hasNext()) { VectorTuple tuple = itr.next(); ...
@Test public void intersection() { SparseVector a = generateVectorA(); SparseVector b = generateVectorB(); SparseVector c = generateVectorC(); SparseVector empty = generateEmptyVector(); assertArrayEquals(a.intersection(b), new int[]{0,1,4,5,8}); assertArrayEquals(a....
public MonitorBuilder group(String group) { this.group = group; return getThis(); }
@Test void group() { MonitorBuilder builder = MonitorBuilder.newBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldReturnValuesForOpenStartBounds_fetchAll() { // Given: final Range<Instant> start = Range.open( NOW, NOW.plusSeconds(10) ); when(keyValueIterator.hasNext()) .thenReturn(true, true, true, false); when(keyValueIterator.next()) .thenReturn(new ...
@Override public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { String originalString = values[0].execute(); String mode = null; // default if (values.length > 1) { mode = values[1].execute(); } if(StringUtils...
@Test public void testChangeCaseWrongMode() throws Exception { String returnValue = execute("myUpperTest", "Wrong"); assertEquals("myUpperTest", returnValue); }
public static void removeDupes( final List<CharSequence> suggestions, List<CharSequence> stringsPool) { if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i...
@Test public void testRemoveDupesNoDupes() throws Exception { ArrayList<CharSequence> list = new ArrayList<>(Arrays.<CharSequence>asList("typed", "something", "banana", "car")); IMEUtil.removeDupes(list, mStringPool); Assert.assertEquals(4, list.size()); Assert.assertEquals("typed", list.get(0...
public String create(final String secret, final String bucket, String region, final String key, final String method, final long expiry) { if(StringUtils.isBlank(region)) { // Only for AWS switch(session.getSignatureVersion()) { case AWS4HMACSHA256: // ...
@Test public void testCreateEuCentral() throws Exception { final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC")); expiry.add(Calendar.MILLISECOND, (int) TimeUnit.DAYS.toMillis(7)); final String url = new S3PresignedUrlProvider(session).create(PROPERTIES.get("s3.secret"), ...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() != ChatMessageType.SPAM && event.getType() != ChatMessageType.GAMEMESSAGE && event.getType() != ChatMessageType.MESBOX) { return; } final var msg = event.getMessage(); if (WOOD_CUT_PATTERN.matcher(msg).matches()) { ...
@Test public void testLogs() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", "You get some logs.", "", 0); woodcuttingPlugin.onChatMessage(chatMessage); assertNotNull(woodcuttingPlugin.getSession()); }
public static HttpClient create() { return new HttpClientConnect(new HttpConnectionProvider()); }
@Test void testConnectionNoIdleTimeElasticPool() throws Exception { ConnectionProvider provider = ConnectionProvider.create("testConnectionNoIdleTimeElasticPool", Integer.MAX_VALUE); ChannelId[] ids = doTestConnectionIdleTime(provider); assertThat(ids[0]).isEqualTo(ids[1]); }
@Override public double getDoubleValue() { checkValueType(DOUBLE); return measure.getDoubleValue(); }
@Test public void get_double_value() { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); assertThat(measure.getDoubleValue()).isEqualTo(1d); }
static boolean isSupportedProtocol(URL url) { String protocol = url.getProtocol().toLowerCase(java.util.Locale.ENGLISH); return protocol.equals(HTTPConstants.PROTOCOL_HTTP) || protocol.equals(HTTPConstants.PROTOCOL_HTTPS); }
@Test public void testHttp() throws Exception { Assertions.assertTrue(AuthManager.isSupportedProtocol(new URL("http:"))); }
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) { SinkConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!existingC...
@Test public void testMergeDifferentResources() { SinkConfig sinkConfig = createSinkConfig(); Resources resources = new Resources(); resources.setCpu(0.3); resources.setRam(1232L); resources.setDisk(123456L); SinkConfig newSinkConfig = createUpdatedSinkConfig("resourc...
@SuppressWarnings("all") public static boolean isValidDesc(@Nullable String desc) { if (desc == null) return false; if (desc.length() == 0) return false; char first = desc.charAt(0); if (first == '(') { try { Type methodType = Type.getMethodType(desc); methodType.getArgumentTypes(); method...
@Test void testIsValidDesc() { assertTrue(Types.isValidDesc("([I[[J[[I)V"), "method desc"); assertTrue(Types.isValidDesc("[I"), "array desc"); assertTrue(Types.isValidDesc("Ljava/lang/String;"), "object desc"); // assertTrue(Types.isValidDesc("LLLLj/av/a/la/ng/S/t/ri/n/g;"), "ugly but valid"); assertTrue(T...
public MessageType union(MessageType toMerge) { return union(toMerge, true); }
@Test public void testMergeSchemaWithOriginalType() throws Exception { MessageType t5 = new MessageType( "root1", new GroupType(REQUIRED, "g1", LIST, new PrimitiveType(OPTIONAL, BINARY, "a")), new GroupType(REQUIRED, "g2", new PrimitiveType(OPTIONAL, BINARY, "b"))); MessageType t6 = ne...
@Override public List<Long> selectAllComputeNodes() { if (!usedComputeNode) { return Collections.emptyList(); } List<Long> nodeIds = availableID2ComputeNode.values().stream() .map(ComputeNode::getId) .collect(Collectors.toList()); nodeIds....
@Test public void testChooseAllComputedNodes() { DefaultWorkerProvider workerProvider; List<Long> computeNodes; workerProvider = new DefaultWorkerProvider(id2Backend, id2ComputeNode, availableId2Backend, availableId2ComputeNode, false); comput...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultMappingKey) { DefaultMappingKey that = (DefaultMappingKey) obj; return Objects.equals(address, that.address); } return false; }
@Test public void testEquals() { IpPrefix ip1 = IpPrefix.valueOf(IP_ADDRESS_1); MappingAddress address1 = MappingAddresses.ipv4MappingAddress(ip1); MappingKey key1 = DefaultMappingKey.builder() .withAddress(address1) .build(); ...
@Override public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) { log.trace("compiling {} {}", intent, installable); ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint(); ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint(); ...
@Test public void testBandwidthConstrainedIntentSuccess() { final double bpsTotal = 1000.0; final double bpsToReserve = 100.0; final ResourceService resourceService = MockResourceService.makeCustomBandwidthResourceService(bpsTotal); final List<Constraint> constraints ...
@Override public Array getArray(final int columnIndex) throws SQLException { return (Array) mergeResultSet.getValue(columnIndex, Array.class); }
@Test void assertGetArrayWithColumnIndex() throws SQLException { Array array = mock(Array.class); when(mergeResultSet.getValue(1, Array.class)).thenReturn(array); assertThat(shardingSphereResultSet.getArray(1), is(array)); }
static boolean hasPartitionsWithIsrGreaterThanReplicas(Cluster cluster) { for (String topic : cluster.topics()) { for (PartitionInfo partitionInfo : cluster.partitionsForTopic(topic)) { int numISR = partitionInfo.inSyncReplicas().length; if (numISR > partitionInfo.replicas().length) { ...
@Test public void testHasPartitionsWithIsrGreaterThanReplicas() { Cluster cluster = getCluster(Arrays.asList(new TopicPartition(TOPIC0, 0), new TopicPartition(TOPIC0, 1))); // Verify: No signal when the cluster has all replicas in sync. assertFalse(MonitorUtils.hasPartitionsWithIsrGreaterThanReplicas(clu...
@Override public CheckResult runCheck() { try { // Create an absolute range from the relative range to make sure it doesn't change during the two // search requests. (count and find messages) // This is needed because the RelativeRange computes the range from NOW on every...
@Test public void testRunCheckLessNegative() throws Exception { final MessageCountAlertCondition.ThresholdType type = MessageCountAlertCondition.ThresholdType.LESS; final MessageCountAlertCondition messageCountAlertCondition = getConditionWithParameters(type, threshold); searchCountShouldR...