focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public R next() { do { R r = currentTraverser.next(); if (r != null) { return r; } currentTraverser = nextTraverser(); } while (currentTraverser != NULL_TRAVERSER); return null; }
@Test public void when_flatMapToNullTraverser_then_skipOverToNext() { // This test would fail, if the internal FlatMappingTraverser.NULL_TRAVERSER instance // would be the same (as per == operator) as the instance returned by Traversers.empty() FlatMappingTraverser<Integer, String> trav = ...
public List<String> splitSql(String text) { List<String> queries = new ArrayList<>(); StringBuilder query = new StringBuilder(); char character; boolean multiLineComment = false; boolean singleLineComment = false; boolean singleQuoteString = false; boolean doubleQuoteString = false; fo...
@Test void testCustomSplitter_2() { SqlSplitter sqlSplitter = new SqlSplitter("#"); List<String> sqls = sqlSplitter.splitSql("show tables;\n#comment_1"); assertEquals(1, sqls.size()); assertEquals("show tables", sqls.get(0)); sqls = sqlSplitter.splitSql("show tables;\n#comment_1"); assertEqua...
List<JobFilter> getFilters() { return filters; }
@Test void jobDefaultFiltersHasDefaultJobFilterAndRetryFilter() { JobDefaultFilters jobDefaultFilters = new JobDefaultFilters(); assertThat(jobDefaultFilters.getFilters()) .hasAtLeastOneElementOfType(DefaultJobFilter.class) .hasAtLeastOneElementOfType(RetryFilter.clas...
@Override public Optional<SubflowExecutionResult> createSubflowExecutionResult( RunContext runContext, TaskRun taskRun, io.kestra.core.models.flows.Flow flow, Execution execution ) { // we only create a worker task result when the execution is terminated if (!task...
@Test void shouldNotReturnResultForExecutionNotTerminated() { TaskRun taskRun = TaskRun .builder() .state(State.of(State.Type.CREATED, Collections.emptyList())) .build(); Optional<SubflowExecutionResult> result = new Subflow().createSubflowExecutionResult( ...
static void dissectFrame( final DriverEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); builder.append(": address="); enc...
@Test void dissectFrameTypeNak() { internalEncodeLogHeader(buffer, 0, 3, 3, () -> 3_000_000_000L); final int socketAddressOffset = encodeSocketAddress( buffer, LOG_HEADER_LENGTH, new InetSocketAddress("localhost", 8888)); final NakFlyweight flyweight = new NakFlyweight(); ...
public static void execute(Task task) { try { task.start(); task.doPrivileged(); } finally { task.stop(); } }
@Test public void allow_everything_in_privileged_block_only() { UserSessionCatcherTask catcher = new UserSessionCatcherTask(); DoPrivileged.execute(catcher); // verify the session used inside Privileged task assertThat(catcher.userSession.isLoggedIn()).isFalse(); assertThat(catcher.userSession.h...
public Optional<String> retrieveTitle(final GRN itemGrn, final SearchUser searchUser) { if (isSpecialView(itemGrn)) { final ViewResolverDecoder decoder = new ViewResolverDecoder(itemGrn.entity()); if (decoder.isResolverViewId()) { final ViewResolver viewResolver = viewRes...
@Test void testReturnsEmptyOptionalOnEmptyEntryInCatalog() throws Exception { doReturn(Optional.empty()).when(catalog).getEntry(any()); assertTrue(toTest.retrieveTitle(grn, searchUser).isEmpty()); }
@Override public DataflowPipelineJob run(Pipeline pipeline) { // Multi-language pipelines and pipelines that include upgrades should automatically be upgraded // to Runner v2. if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) { List<String> experiments = fi...
@Test public void testUpdateAlreadyUpdatedPipeline() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.setUpdate(true); options.setJobName("oldJobName"); Dataflow mockDataflowClient = options.getDataflowClient(); Dataflow.Projects.Locations.Jobs.Create mockRequ...
@Override public SortedSet<Path> convertFrom(String value) { if (value == null) { throw new ParameterException("Path list must not be null."); } return Arrays.stream(value.split(SEPARATOR)) .map(StringUtils::trimToNull) .filter(Objects::...
@Test(expected = ParameterException.class) public void testConvertFromNull() { converter.convertFrom(null); }
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request) throws Exception { BeamFnApi.ProcessBundleResponse.Builder response = BeamFnApi.ProcessBundleResponse.newBuilder(); BundleProcessor bundleProcessor = bundleProcessorCache.get( request, ...
@Test public void testPTransformFinishExceptionsArePropagated() throws Exception { BeamFnApi.ProcessBundleDescriptor processBundleDescriptor = BeamFnApi.ProcessBundleDescriptor.newBuilder() .putTransforms( "2L", RunnerApi.PTransform.newBuilder() ...
@Override public void upgrade() { final FindIterable<Document> documentsWithMissingFields = collection.find(or(not(exists(ContentPack.FIELD_META_ID)), not(exists(ContentPack.FIELD_META_REVISION)))); for (Document document : documentsWithMissingFields) { final ObjectId objectId = document...
@Test @MongoDBFixtures("V20180718155800_AddContentPackIdAndRevTest.json") public void upgrade() { final MongoCollection<Document> collection = mongodb.mongoConnection() .getMongoDatabase() .getCollection(ContentPackPersistenceService.COLLECTION_NAME); final Bson f...
@Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { switch (request.getCode()) { case RequestCode.UPDATE_AND_CREATE_TOPIC: return this.updateAndCreateTopic(ctx, request); case Re...
@Test public void testProcessRequest_fail() throws RemotingCommandException, UnknownHostException { RemotingCommand request = createResumeCheckHalfMessageCommand(); when(messageStore.selectOneMessageByOffset(any(Long.class))).thenReturn(createSelectMappedBufferResult()); RemotingCommand resp...
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test public void isEqualTo_WithoutToleranceParameter_Success() { assertThat(array(2.2f, 5.4f, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0f, -0.0f)) .isEqualTo(array(2.2f, 5.4f, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0f, -0.0f)); }
public static String getIntfNameFromPciAddress(Port port) { String intfName; if (port.getProfile() == null || port.getProfile().isEmpty()) { log.error("Port profile is not found"); return null; } if (!port.getProfile().containsKey(PCISLOT) || Str...
@Test public void testGetIntfNameFromPciAddress() { String expectedIntfName1 = "enp5s8"; String expectedIntfName2 = "enp5s8f3"; assertNull(getIntfNameFromPciAddress(openstackPort)); assertEquals(expectedIntfName1, getIntfNameFromPciAddress(openstackSriovPort1)); assertEqual...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testParseCorruptedRecord() throws Exception { buildFetcher(); assignFromUser(singleton(tp0)); ByteBuffer buffer = ByteBuffer.allocate(1024); DataOutputStream out = new DataOutputStream(new ByteBufferOutputStream(buffer)); byte magic = RecordBatch.MAGIC_VAL...
public static ObjectMapper newObjectMapper() { final ObjectMapper mapper = new ObjectMapper(); return configure(mapper); }
@Test void objectMapperSerializesNullValues() throws IOException { final ObjectMapper mapper = Jackson.newObjectMapper(); final Issue1627 pojo = new Issue1627(null, null); final String json = "{\"string\":null,\"uuid\":null}"; assertThat(mapper.writeValueAsString(pojo)).isEqualTo(js...
@Override public void filter(ContainerRequestContext requestContext) { if (isInternalRequest(requestContext)) { log.trace("Skipping authentication for internal request"); return; } try { log.debug("Authenticating request"); BasicAuthCredential...
@Test public void testSecurityContextSet() throws IOException, URISyntaxException { File credentialFile = setupPropertyLoginFile(true); JaasBasicAuthFilter jaasBasicAuthFilter = setupJaasFilter("KafkaConnect", credentialFile.getPath()); ContainerRequestContext requestContext = setMock("Basic...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { MessageNode messageNode = chatMessage.getMessageNode(); boolean update = false; switch (chatMessage.getType()) { case TRADEREQ: if (chatMessage.getMessage().contains("wishes to trade with you.")) { notifier.notify(config.notifyOn...
@Test public void testHighlightOwnName() { Player player = mock(Player.class); when(player.getName()).thenReturn("Logic Knot"); when(client.getLocalPlayer()).thenReturn(player); when(config.highlightOwnName()).thenReturn(true); MessageNode messageNode = mock(MessageNode.class); when(messageNode.getValue...
public boolean remove(@Nonnull T toRemove) { final int elementIndex = toRemove.getInternalIndex(); removeInternal(elementIndex); return elementIndex == getHeadElementIndex(); }
@Test void testRemove() { HeapPriorityQueue<TestElement> priorityQueue = newPriorityQueue(1); final long key = 4711L; final long priorityValue = 42L; final TestElement testElement = new TestElement(key, priorityValue); assertThat(priorityQueue.add(testElement)).isTrue(); ...
public void setFallback(ApacheHttpClientFallback fallback) { AssertUtil.notNull(fallback, "fallback cannot be null"); this.fallback = fallback; }
@Test(expected = IllegalArgumentException.class) public void testConfigSetFallback() { SentinelApacheHttpClientConfig config = new SentinelApacheHttpClientConfig(); config.setFallback(null); }
static void writeResponse(Configuration conf, Writer out, String format, String propertyName) throws IOException, IllegalArgumentException, BadFormatException { if (FORMAT_JSON.equals(format)) { Configuration.dumpConfiguration(conf, propertyName, out); } else if (FORMAT_XML.equals(format))...
@Test public void testWriteXml() throws Exception { StringWriter sw = new StringWriter(); ConfServlet.writeResponse(getTestConf(), sw, "xml"); String xml = sw.toString(); DocumentBuilderFactory docBuilderFactory = XMLUtils.newSecureDocumentBuilderFactory(); DocumentBuilder builder = docBuilderFac...
public static Packet ensureUniqueAndStableStanzaID( final Packet packet, final JID self ) { if ( !JiveGlobals.getBooleanProperty( "xmpp.sid.enabled", true ) ) { return packet; } if ( packet instanceof IQ && !JiveGlobals.getBooleanProperty( "xmpp.sid.iq.enabled", false ) ...
@Test public void testDontOverwriteStanzaIDElement() throws Exception { // Setup fixture. final Packet input = new Message(); final JID self = new JID( "foobar" ); final String notExpected = "de305d54-75b4-431b-adb2-eb6b9e546013"; final Element toOverwrite = input.getElem...
public static String decode(String str, Charset charset) { return decode(str, charset, true); }
@Test public void issue3063Test() throws UnsupportedEncodingException { // https://github.com/dromara/hutool/issues/3063 final String s = "测试"; final String expectedDecode = "%FE%FF%6D%4B%8B%D5"; final String s1 = URLUtil.encode(s, StandardCharsets.UTF_16); assertEquals(expectedDecode, s1); final String ...
public NumericIndicator previous(int barCount) { return NumericIndicator.of(new PreviousValueIndicator(this, barCount)); }
@Test public void previous() { final NumericIndicator numericIndicator = NumericIndicator.of(cp1); final Indicator<Num> previous = numericIndicator.previous(); assertNumEquals(cp1.getValue(0), previous.getValue(1)); final Indicator<Num> previous3 = numericIndicator.previous(3); ...
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException { byte[] bytes = pollEntryBytes(timeout); if (bytes == null) { return null; } return DLQEntry.deserialize(bytes); }
@Test public void testRereadFinalBlock() throws Exception { Event event = createEventWithConstantSerializationOverhead(Collections.emptyMap()); // Fill event with not quite enough characters to fill block. Fill event with valid RecordType characters - this // was the cause of https://github...
boolean filterUrl(HTTPSamplerBase sampler) { String domain = sampler.getDomain(); if (domain == null || domain.isEmpty()) { return false; } String url = generateMatchUrl(sampler); CollectionProperty includePatterns = getIncludePatterns(); if (!includePatterns...
@Test public void testFilter3() throws Exception { sampler.setPath("header.gif"); sampler.setDomain("jakarta.org"); assertFalse(control.filterUrl(sampler), "Should not match header.gif"); }
static List<String> locateScripts(ArgsMap argsMap) { String script = argsMap.get(SCRIPT); String scriptDir = argsMap.get(SCRIPT_DIR); List<String> scripts = new ArrayList<>(); if (script != null) { StringTokenizer tokenizer = new StringTokenizer(script, ":"); if (log.isDebugEnabled()) { ...
@Test void locateScriptsSingle() { ArgsMap argsMap = new ArgsMap(new String[] {"script=script1"}); List<String> scripts = Main.locateScripts(argsMap); assertEquals(1, scripts.size()); }
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testNoOwnerLoadData() throws IllegalAccessException { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); FieldUtils.writeDeclaredField(transferShedder, "channel", channel, true); var ctx = setupContext(); ...
public static SqlOperator convert(final CombineType combineType) { Preconditions.checkState(REGISTRY.containsKey(combineType), "Unsupported combine type: `%s`", combineType); return REGISTRY.get(combineType); }
@Test void assertConvertSuccess() { assertThat(CombineOperatorConverter.convert(CombineType.UNION_ALL), is(SqlStdOperatorTable.UNION_ALL)); assertThat(CombineOperatorConverter.convert(CombineType.UNION), is(SqlStdOperatorTable.UNION)); assertThat(CombineOperatorConverter.convert(CombineType....
@Override public Column convert(BasicTypeDefine typeDefine) { try { return super.convert(typeDefine); } catch (SeaTunnelRuntimeException e) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefi...
@Test public void testConvertOtherString() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("text").dataType("text").build(); Column column = KingbaseTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName...
@VisibleForTesting void validateEmailUnique(Long id, String email) { if (StrUtil.isBlank(email)) { return; } AdminUserDO user = userMapper.selectByEmail(email); if (user == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的用户 if (id == null...
@Test public void testValidateEmailUnique_emailExistsForUpdate() { // 准备参数 Long id = randomLongId(); String email = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); // 调用,校验异常 assertServiceException(() -> userService.va...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentExecutor, TokenSecretAuthData authData, PhotosContainerResource data) throws Exception { if (data == null) { // Nothing to do return ImportResult.OK; } BackblazeDataTransferC...
@Test public void testNullPhotosAndAlbums() throws Exception { PhotosContainerResource data = mock(PhotosContainerResource.class); when(data.getAlbums()).thenReturn(null); when(data.getPhotos()).thenReturn(null); BackblazePhotosImporter sut = new BackblazePhotosImporter(monitor, dataStore, st...
public static void mergeDeepLinkProperty(JSONObject properties) { try { if (mDeepLinkProcessor != null) { mDeepLinkProcessor.mergeDeepLinkProperty(properties); } } catch (Exception ex) { SALog.printStackTrace(ex); } }
@Test public void mergeDeepLinkProperty() { JSONObject jsonObject = new JSONObject(); DeepLinkManager.mergeDeepLinkProperty(jsonObject); }
static <T> CompletionStage<T> executeCompletionStageSupplier(Observation observation, Supplier<CompletionStage<T>> supplier) { return decorateCompletionStageSupplier(observation, supplier).get(); }
@Test public void shouldExecuteCompletionStageSupplier() throws Throwable { given(helloWorldService.returnHelloWorld()).willReturn("Hello world"); Supplier<CompletionStage<String>> completionStageSupplier = () -> CompletableFuture.supplyAsync(helloWorldService::returnHelloWorld); ...
public int getDepth(Throwable ex) { return getDepth(ex.getClass(), 0); }
@Test public void foundImmediatelyWithString() { RollbackRule rr = new RollbackRule(Exception.class.getName()); assertThat(rr.getDepth(new Exception())).isEqualTo(0); }
public String parseBodyToHTML() throws IOException, SAXException, TikaException { ContentHandler handler = new BodyContentHandler(new ToXMLContentHandler()); AutoDetectParser parser = new AutoDetectParser(); Metadata metadata = new Metadata(); try (InputStream stream = ContentHandlerExa...
@Test public void testParseBodyToHTML() throws IOException, SAXException, TikaException { String result = example .parseBodyToHTML() .trim(); assertNotContained("<html", result); assertNotContained("<head>", result); assertNotContained("<meta name=\"d...
public Tree<T> filterNew(Filter<Tree<T>> filter) { return cloneTree().filter(filter); }
@Test public void filterNewTest() { final Tree<String> tree = TreeUtil.buildSingle(nodeList, "0"); // 经过过滤,生成新的树 Tree<String> newTree = tree.filterNew((t) -> { final CharSequence name = t.getName(); return null != name && name.toString().contains("店铺"); }); List<String> ids = new ArrayList<>(); new...
public Struct put(String fieldName, Object value) { Field field = lookupField(fieldName); return put(field, value); }
@Test public void testInvalidFieldType() { assertThrows(DataException.class, () -> new Struct(FLAT_STRUCT_SCHEMA).put("int8", "should fail because this is a string, not int8")); }
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testDistinctAggregations() { analyze("SELECT COUNT(DISTINCT a), SUM(a) FROM t1"); }
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); DateColumnStatsDataInspector aggregateData = dateInspectorFromStats(aggregateColStats); DateColum...
@Test public void testMergeNullWithNonNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(Date.class) .low(null) .high(null) .numNulls(0) .numDVs(0) .build()); ColumnStatisticsObj newObj = createColumnStatisticsObj(new ColStatsBu...
public int maxValue() { final int initialValue = this.initialValue; int max = 0 == size ? initialValue : Integer.MIN_VALUE; final int[] entries = this.entries; @DoNotSub final int length = entries.length; for (@DoNotSub int i = 1; i < length; i += 2) { f...
@Test void shouldHaveNoMaxValueForEmptyCollection() { assertEquals(INITIAL_VALUE, map.maxValue()); }
@Override public void deleteTenant(Long id) { // 校验存在 validateUpdateTenant(id); // 删除 tenantMapper.deleteById(id); }
@Test public void testDeleteTenant_system() { // mock 数据 TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackageId(PACKAGE_ID_SYSTEM)); tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbTenant.getId(); // 调用, 并断言异常 assertServiceE...
@Override @Transactional(rollbackFor = Exception.class) public void updateCodegen(CodegenUpdateReqVO updateReqVO) { // 校验是否已经存在 if (codegenTableMapper.selectById(updateReqVO.getTable().getId()) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 校验主表字段存在 ...
@Test public void testUpdateCodegen_sub_columnNotExists() { // mock 数据 CodegenTableDO subTable = randomPojo(CodegenTableDO.class, o -> o.setTemplateType(CodegenTemplateTypeEnum.SUB.getType()) .setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableM...
public void addDependency(T from, T to) { if (from == null || to == null || from.equals(to)) { throw new IllegalArgumentException("Invalid parameters"); } long stamp = lock.writeLock(); try { if (addOutgoingEdge(from, to)) { addIncomingEdge(to, from); } ...
@Test(expectedExceptions = IllegalArgumentException.class) public void testAdNull() { new DependencyGraph<>().addDependency("N", null); }
@Override public Iterator<QueryableEntry> iterator() { return new It(); }
@Test(expected = UnsupportedOperationException.class) public void removeUnsupported() { Set<QueryableEntry> entries = generateEntries(100000); AndResultSet resultSet = new AndResultSet(entries, null, asList(Predicates.alwaysTrue())); resultSet.remove(resultSet.iterator().next()); }
@Override public void run() { if (!redoService.isConnected()) { LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task"); return; } try { redoForInstances(); redoForSubscribes(); } catch (Exception e) { ...
@Test void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set<SubscriberRedoData> mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); red...
public int registerUser(final User user) throws SQLException { var sql = "insert into USERS (username, password) values (?,?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql) ) { preparedStatement.setString(1, user.g...
@Test void registerShouldFail() throws SQLException { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); userTableModule.registerUser(user); assertThrows(SQLException.class, () -> userTableModule.registerUser(user...
@Override public void send(Message msg, List<RoutingNode> recipients) { for (RoutingNode recipient : recipients) { new MessageEnvelope(this, msg, recipient).send(); } }
@Test void requireThatUnknownServiceRepliesWithNoAddressForService() throws InterruptedException { final Server server = new Server(new LocalWire()); final SourceSession source = server.newSourceSession(); final Message msg = new SimpleMessage("foo").setRoute(Route.parse("bar")); as...
public void writeInt4(final int value) { byteBuf.writeIntLE(value); }
@Test void assertWriteInt4() { new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).writeInt4(1); verify(byteBuf).writeIntLE(1); }
public static Document readDocument(@Nonnull final InputStream stream) throws ExecutionException, InterruptedException { return readDocumentAsync(stream).get(); }
@Test public void testDocumentException() throws Exception { // Setup test fixture. final InputStream input = new ByteArrayInputStream("this is not valid XML".getBytes(StandardCharsets.UTF_8)); final ExecutionException result; try { // Execute system under test. ...
public static boolean isUnclosedQuote(final String line) { // CHECKSTYLE_RULES.ON: CyclomaticComplexity int quoteStart = -1; for (int i = 0; i < line.length(); ++i) { if (quoteStart < 0 && isQuoteChar(line, i)) { quoteStart = i; } else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !...
@Test public void shouldFindUnclosedQuote_manyQuote() { // Given: final String line = "some line 'this is in a quote''''"; // Then: assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(true)); }
protected void handshakeFailure(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn("{} TLS handshake failed:", ctx.channel(), cause); ctx.close(); }
@Test public void testHandshakeFailure() { ChannelHandler alpnHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { fail(); } ...
@Override public Stream<FileSlice> getLatestUnCompactedFileSlices(String partitionPath) { return execute(partitionPath, preferredView::getLatestUnCompactedFileSlices, (path) -> getSecondaryView().getLatestUnCompactedFileSlices(path)); }
@Test public void testGetLatestUnCompactedFileSlices() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; when(primary.getLatestUnCompactedFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestUnCompactedF...
public boolean shouldShow(@Nullable Keyboard.Key pressedKey) { return pressedKey != null && shouldShow(pressedKey.getPrimaryCode()); }
@Test public void testHandlesNullKey() { final OnKeyWordHelper helper = new OnKeyWordHelper("test".toCharArray()); Assert.assertFalse(helper.shouldShow(null)); }
public EndpointResponse streamQuery( final KsqlSecurityContext securityContext, final KsqlRequest request, final CompletableFuture<Void> connectionClosedFuture, final Optional<Boolean> isInternalRequest, final MetricsCallbackHolder metricsCallbackHolder, final Context context ) { ...
@Test public void shouldThrowOnDenyListedStreamProperty() { // Given: when(mockStatementParser.<Query>parseSingleStatement(PULL_QUERY_STRING)).thenReturn(query); testResource = new StreamedQueryResource( mockKsqlEngine, ksqlRestConfig, mockStatementParser, commandQueue, ...
@Override public void shutdown(final Callback<None> callback) { info(_log, "shutting down dynamic client"); _balancer.shutdown(() -> { info(_log, "dynamic client shutdown complete"); callback.onSuccess(None.none()); }); TimingKey.unregisterKey(TIMING_KEY); }
@Test(groups = { "small", "back-end" }) public void testShutdown() throws URISyntaxException, InterruptedException { LoadBalancerMock balancer = new LoadBalancerMock(true); DynamicClient client = new DynamicClient(balancer, null, true); final CountDownLatch latch = new CountDownLatch(1); asse...
@Override public float readFloat(@Nonnull String fieldName) throws IOException { FieldDefinition fd = cd.getField(fieldName); if (fd == null) { return 0f; } switch (fd.getType()) { case FLOAT: return super.readFloat(fieldName); case...
@Test(expected = IncompatibleClassChangeError.class) public void testReadFloat_IncompatibleClass() throws Exception { reader.readFloat("string"); }
@Override public List<String> splitAndEvaluate() { return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : flatten(evaluate(GroovyUtils.split(handlePlaceHolder(inlineExpression)))); }
@Test void assertEvaluateForLiteral() { List<String> expected = TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", PropertiesBuilder.build( new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, "t_order_${'xx'}"))).splitAndEvaluate(); assertThat(...
public static Object convertAvroFormat( FieldType beamFieldType, Object avroValue, BigQueryUtils.ConversionOptions options) { TypeName beamFieldTypeName = beamFieldType.getTypeName(); if (avroValue == null) { if (beamFieldType.getNullable()) { return null; } else { throw new Il...
@Test public void testSubMilliPrecisionTruncated() { long millis = 123456789L; assertThat( BigQueryUtils.convertAvroFormat(FieldType.DATETIME, millis * 1000 + 123, TRUNCATE_OPTIONS), equalTo(new Instant(millis))); }
@Override public FileObject[] findJarFiles() throws KettleFileException { return findJarFiles( searchLibDir ); }
@Test public void testFindJarFiles_ExceptionThrows() { String nullFolder = null; String expectedMessage = "Unable to list jar files in plugin folder '" + nullFolder + "'"; plFolder = new PluginFolder( nullFolder, false, true ); try { plFolder.findJarFiles(); fail( "KettleFileException was...
@Override public MetricsCollector create(final MetricConfiguration metricConfig) { switch (metricConfig.getType()) { case COUNTER: return new PrometheusMetricsCounterCollector(metricConfig); case GAUGE: return new PrometheusMetricsGaugeCollector(metric...
@Test void assertCreateGaugeMetricFamilyCollector() { MetricConfiguration config = new MetricConfiguration("test_summary", MetricCollectorType.GAUGE_METRIC_FAMILY, null, Collections.emptyList(), Collections.emptyMap()); assertThat(new PrometheusMetricsCollectorFactory().create(config), instanceOf(Pr...
@Override public Connection getConnection() throws SQLException { return dataSourceProxyXA.getConnection(); }
@Test public void testGetConnection() throws SQLException { // Mock Driver driver = Mockito.mock(Driver.class); JDBC4MySQLConnection connection = Mockito.mock(JDBC4MySQLConnection.class); Mockito.when(connection.getAutoCommit()).thenReturn(true); DatabaseMetaData metaData = M...
public static int getCpuCores() { // 找不到文件或者异常,则去物理机的核心数 int cpu = RpcConfigs.getIntValue(RpcOptions.SYSTEM_CPU_CORES); return cpu > 0 ? cpu : Runtime.getRuntime().availableProcessors(); }
@Test public void getCpuCores() { Assert.assertTrue(SystemInfo.getCpuCores() > 0); }
@Override public void clear() { ipv4Tree = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory()); ipv6Tree = new ConcurrentRadixTree<>(new DefaultCharArrayNodeFactory()); }
@Test public void testClear() { radixTree.clear(); assertThat("Incorrect size of radix tree for IPv4 maps", radixTree.size(IpAddress.Version.INET), is(0)); assertThat("Incorrect size of radix tree for IPv6 maps", radixTree.size(IpAddress.Version.INET6), is(0))...
@Override public CompletableFuture<T> toCompletableFuture() { return _task.toCompletionStage().toCompletableFuture(); }
@Test public void testToCompletableFuture_success() throws Exception { CompletionStage completableFuture = createTestStage(TESTVALUE1).toCompletableFuture(); assertEquals(completableFuture.toCompletableFuture().get(), TESTVALUE1); }
@Override public void removeListener(int listenerId) { super.removeListener(listenerId); String topicName = getNameByListenerId(listenerId); if (topicName != null) { RTopic topic = getTopic(topicName); removeListenerId(topicName, listenerId); topic.remove...
@Test public void testRemoveListener() { RMapCache<Long, String> rMapCache = redisson.getMapCache("test"); rMapCache.trySetMaxSize(5); AtomicBoolean removed = new AtomicBoolean(); rMapCache.addListener(new EntryRemovedListener() { @Override public void onRemov...
public String getEcosystem(DefCveItem cve) { final int[] ecosystemMap = new int[ECOSYSTEMS.length]; cve.getCve().getDescriptions().stream() .filter((langString) -> (langString.getLang().equals("en"))) .forEachOrdered((langString) -> search(langString.getValue(), ecosystem...
@Test public void testSubsetKeywordsDoNotMatch() throws IOException { DescriptionEcosystemMapper mapper = new DescriptionEcosystemMapper(); String value = "Wonder if java senses the gc."; // i.e. does not match 'java se' assertNull(mapper.getEcosystem(asCve(value))); }
@Override public Executor getExecutor(final URL url) { try { return SpringBeanUtils.getInstance().getBean(ShenyuThreadPoolExecutor.class); } catch (NoSuchBeanDefinitionException t) { throw new ShenyuException("shared thread pool is not enable, config ${shenyu.sharedPool.enabl...
@Test public void testGetExecutor() { ShenyuThreadPoolExecutor shenyuThreadPoolExecutor = new ShenyuThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS, new MemorySafeTaskQueue<>(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); SpringBeanUtils....
public Options getPaimonOptions() { return this.paimonOptions; }
@Test public void testCreatePaimonConnectorWithS3() { Map<String, String> properties = new HashMap<>(); properties.put("paimon.catalog.warehouse", "s3://bucket/warehouse"); properties.put("paimon.catalog.type", "filesystem"); String accessKeyValue = "s3_access_key"; String se...
public void append(long offset, int position) { lock.lock(); try { if (isFull()) throw new IllegalArgumentException("Attempt to append to a full index (size = " + entries() + ")."); if (entries() == 0 || offset > lastOffset) { log.trace("Adding in...
@Test public void appendTooMany() { for (int i = 0; i < index.maxEntries(); ++i) { long offset = index.baseOffset() + i + 1; index.append(offset, i); } assertWriteFails("Append should fail on a full index", index, index.maxEntries() + 1); }
public static <InputT> UsingBuilder<InputT> of(PCollection<InputT> input) { return new UsingBuilder<>(DEFAULT_NAME, input); }
@SuppressWarnings("unchecked") @Test public void testBuild_NegatedPredicate() { final PCollection<Integer> dataset = TestUtils.createMockDataset(TypeDescriptors.integers()); final Split.Output<Integer> split = Split.of(dataset).using((UnaryPredicate<Integer>) what -> what % 2 == 0).output(); fi...
public Collection<SQLToken> generateSQLTokens(final TablesContext tablesContext, final SetAssignmentSegment setAssignmentSegment) { String tableName = tablesContext.getSimpleTables().iterator().next().getTableName().getIdentifier().getValue(); EncryptTable encryptTable = encryptRule.getEncryptTable(tabl...
@Test void assertGenerateSQLTokenWithUpdateParameterMarkerExpressionSegment() { when(assignmentSegment.getValue()).thenReturn(mock(ParameterMarkerExpressionSegment.class)); assertThat(tokenGenerator.generateSQLTokens(tablesContext, setAssignmentSegment).size(), is(1)); }
String getLockName(String namespace, String name) { return "lock::" + namespace + "::" + kind() + "::" + name; }
@Test /* * Verifies that the lock is released by a call to `releaseLockAndTimer`. * The call is made through a chain of futures ending with `eventually` after a failed execution via a handled exception in the `Callable`. */ void testWithLockCallableHandledExceptionReleasesLock(VertxTestContext c...
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null!"); byte[] ...
@Test public void testRename() { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyFor...
public void expectErrorsForTag(String tag) { if (UNPREVENTABLE_TAGS.contains(tag)) { throw new AssertionError("Tag `" + tag + "` is already suppressed."); } expectedTags.add(tag); }
@Test public void testNoExpectedTagFailsTest() { expectedException.expect(AssertionError.class); rule.expectErrorsForTag("Mytag"); }
@Override public boolean contains(Object o) { if (!(o instanceof Integer)) { throw new ClassCastException("PartitionIdSet can be only used with Integers"); } return bitSet.get((Integer) o); }
@Test(expected = ClassCastException.class) public void test_contains_whenNotInteger() { partitionIdSet.contains(new Object()); }
public static String extractAttributeNameNameWithoutArguments(String attributeNameWithArguments) { int start = StringUtil.lastIndexOf(attributeNameWithArguments, '['); int end = StringUtil.lastIndexOf(attributeNameWithArguments, ']'); if (start > 0 && end > 0 && end > start) { return...
@Test(expected = IllegalArgumentException.class) public void extractAttributeName_wrongArguments_noOpening() { extractAttributeNameNameWithoutArguments("car.wheelleft]"); }
@Override public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); }
@Test public void validateSmsCode_expired() { // 准备参数 SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { o.setMobile("15601691300"); o.setScene(randomEle(SmsSceneEnum.values()).getScene()); }); // mock 数据 SqlConstants.init(Db...
public CompiledPipeline.CompiledExecution buildExecution() { return buildExecution(false); }
@Test @SuppressWarnings({"unchecked"}) public void testReuseCompiledClasses() throws IOException, InvalidIRException { final FixedPluginFactory pluginFactory = new FixedPluginFactory( () -> null, () -> IDENTITY_FILTER, mockOutputSupplier() ); ...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Compute Engine Tasks"); try (DbSession dbSession = dbClient.openSession(false)) { setAttribute(protobuf, "Total Pending", dbClient.ceQue...
@Test public void test_queue_state_with_default_settings() { when(dbClient.ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.PENDING))).thenReturn(10); when(dbClient.ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.IN_PROGRESS))).thenReturn(1); CeQueueGlobalSection underTest = new CeQueueGloba...
@Override public <R> R run(Action<R, C, E> action) throws E, InterruptedException { return run(action, retryByDefault); }
@Test public void testRetriesExhaustedAndSurfacesFailure() { int maxRetries = 3; int succeedAfterAttempts = 5; try (MockClientPoolImpl mockClientPool = new MockClientPoolImpl(2, RetryableException.class, true, maxRetries)) { assertThatThrownBy( () -> mockClientPool.run(client -...
@Override public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception { final List<String> loggerNames = getLoggerNames(parameters); final Level loggerLevel = getLoggerLevel(parameters); final Duration duration = getDuration(parameters); for (Strin...
@Test void configuresSpecificLevelForALoggerForADuration() throws Exception { // given Level oneEffectiveBefore = logger1.getEffectiveLevel(); Map<String, List<String>> parameters = Map.of( "logger", List.of("logger.one"), "level", List.of("debug"), "dura...
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsAnyOf_primitiveDoubleArray_failure() { expectFailureWhenTestingThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsAnyOf(array(99.99, 999.999)); assertFailureKeys("value of", "expected to contain any of", "testing whethe...
public String generate() { StringBuilder sb = new StringBuilder(); sb.append(firstCharacterAlphabet.charAt(rng.nextInt(firstCharacterAlphabet.length()))); for (int i = 1; i < length; i++) { sb.append(alphabet.charAt(rng.nextInt(alphabet.length()))); } return sb.toS...
@Test public void length() { PasswordGenerator generator = new PasswordGenerator(10, "a", "a"); assertThat(generator.generate(), is("aaaaaaaaaa")); }
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException { final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class); ...
@Test void parseArtifactResolveCancelled() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException { ArtifactResponse artifactResponse = artifactResponseService.buildArtifactResponse(getArtifactResolveRequest("canceled", true, false, SAML_COMBICONNECT, En...
@Override public ManifestTemplate call() throws IOException { Preconditions.checkState(!builtImages.isEmpty(), "no images given"); EventHandlers eventHandlers = buildContext.getEventHandlers(); try (TimerEventDispatcher ignored = new TimerEventDispatcher(eventHandlers, DESCRIPTION); ProgressEventD...
@Test public void testCall_emptyImagesList() throws IOException { try { new BuildManifestListOrSingleManifestStep( buildContext, progressDispatcherFactory, Collections.emptyList()) .call(); Assert.fail(); } catch (IllegalStateException ex) { Assert.assertEquals("no im...
@Override public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); EurekaHttpClient client = null; try { client = clientFactory.newClient(); EurekaHttpResponse<Applications> response = client.getVip(vipAddress); if (v...
@Test public void testHappyCase() { List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); verify(httpClient, times(1)).shutdown(); }
@Override public DenseMatrix matrixMultiply(Matrix other) { if (dim2 == other.getDimension1Size()) { if (other instanceof DenseMatrix) { DenseMatrix otherDense = (DenseMatrix) other; double[][] output = new double[dim1][otherDense.dim2]; for (int ...
@Test public void identityTest() { DenseMatrix a = generateA(); DenseMatrix b = generateB(); DenseMatrix c = generateC(); DenseMatrix d = generateD(); DenseMatrix e = generateE(); DenseMatrix f = generateF(); DenseMatrix eye = identity(10); DenseMatrix...
public NonClosedTracking<RAW, BASE> trackNonClosed(Input<RAW> rawInput, Input<BASE> baseInput) { NonClosedTracking<RAW, BASE> tracking = NonClosedTracking.of(rawInput, baseInput); // 1. match by rule, line, line hash and message match(tracking, LineAndLineHashAndMessage::new); // 2. match issues with ...
@Test public void similar_issues_if_trimmed_messages_match() { FakeInput baseInput = new FakeInput("H1"); Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, " message "); FakeInput rawInput = new FakeInput("H2"); Issue raw = rawInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "message"); ...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvGarbageFree() { // 'StringUtil#escapeCsv()' should return same string object if string didn't changing. assertSame("1", StringUtil.escapeCsv("1", true)); assertSame(" 123 ", StringUtil.escapeCsv(" 123 ", false)); assertSame("\" 123 \"", StringUtil.escapeCsv...
@Override public Optional<Listener> acquire(ContextT context) { return tryAcquire(context).map(delegate -> new Listener() { @Override public void onSuccess() { delegate.onSuccess(); unblock(); } @Override public voi...
@Test public void adaptWhenLimitDecreases() { List<Optional<Limiter.Listener>> listeners = acquireN(blockingLimiter, 4); limit.setLimit(3); listeners.get(0).get().onSuccess(); // Next acquire will reject and block long start = System.nanoTime(); Optional<Limiter.Li...
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatDoubleLiteralWithLargeScale() { assertThat(ExpressionFormatter.formatExpression( new DoubleLiteral(1234.56789876d)), equalTo("1.23456789876E3")); }
@Override public void monitor(RedisServer master) { connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(), master.getPort().intValue(), master.getQuorum().intValue()); }
@Test public void testMonitor() { Collection<RedisServer> masters = connection.masters(); RedisServer master = masters.iterator().next(); master.setName(master.getName() + ":"); connection.monitor(master); }
public void store(byte[] hash) { db.putItem(PutItemRequest.builder() .tableName(tableName) .item(Map.of( KEY_HASH, AttributeValues.fromByteArray(hash), ATTR_TTL, AttributeValues.fromLong(Instant.now().plus(ttl).getEpochSecond()) )) .build()); }
@Test void testStore() { final byte[] hash1 = UUIDUtil.toBytes(UUID.randomUUID()); final byte[] hash2 = UUIDUtil.toBytes(UUID.randomUUID()); assertAll("database should be empty", () -> assertFalse(reportMessageDynamoDb.remove(hash1)), () -> assertFalse(reportMessageDynamoDb.remove(hash2)...
public <T> Future<Iterable<Map.Entry<ByteString, Iterable<T>>>> multimapFetchAllFuture( boolean omitValues, ByteString encodedTag, String stateFamily, Coder<T> elemCoder) { StateTag<ByteString> stateTag = StateTag.<ByteString>of(Kind.MULTIMAP_ALL, encodedTag, stateFamily) .toBuilder() ...
@Test public void testReadMultimapEntriesPaginated() throws Exception { Future<Iterable<Map.Entry<ByteString, Iterable<Integer>>>> future = underTest.multimapFetchAllFuture(false, STATE_KEY_1, STATE_FAMILY, INT_CODER); Mockito.verifyNoMoreInteractions(mockWindmill); Windmill.KeyedGetDataRequest.B...
@Override protected void handlePut(final String listenTo, final ServiceProperties discoveryProperties) { LoadBalancerStateItem<ServiceProperties> oldServicePropertiesItem = _simpleLoadBalancerState.getServiceProperties().get(listenTo); ActivePropertiesResult pickedPropertiesResult = pickActiveProperti...
@Test(dataProvider = "getConfigsAndDistributions") public void testWithCanaryConfigs(ServiceProperties stableConfigs, ServiceProperties canaryConfigs, CanaryDistributionStrategy distributionStrategy, CanaryDistributionProvider.Distribution distribution) { ServiceLoadBalancerS...
@Override protected String throwableProxyToString(IThrowableProxy tp) { final String prefixed = PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX); return CAUSING_PATTERN.matcher(prefixed).replaceAll(CAUSING); }
@Test void placesRootCauseIsFirst() { assertThat(converter.throwableProxyToString(proxy)).matches(Pattern.compile(".+" + "java\\.net\\.SocketTimeoutException: Timed-out reading from socket.+" + "java\\.io\\.IOException: Fairly general error doing some IO.+" + ...
public Map<String, Set<String>> usagesOfProfiles(final Set<String> profilesIds) { Map<String, Set<String>> usagesInIndexSet = new HashMap<>(); profilesIds.forEach(profId -> usagesInIndexSet.put(profId, new HashSet<>())); indexSetsCollection .find(Filters.in(FIELD_PROFILE_ID, ...
@Test public void testReturnsProperUsagesForMultipleProfiles() { Map<String, Set<String>> expectedResult = Map.of( PROFILE1_ID, Set.of("000000000000000000000001", "000000000000000000000011"), PROFILE2_ID, Set.of("000000000000000000000002"), UNUSED_PROFILE_ID, ...
@Override public double calcMinWeightPerDistance() { return 1d / (maxSpeedCalc.calcMax() / SPEED_CONV) / maxPrioCalc.calcMax() + distanceInfluence; }
@Test public void testMaxSpeed() { assertEquals(155, avSpeedEnc.getMaxOrMaxStorableDecimal(), 0.1); assertEquals(1d / 72 * 3.6, createWeighting(createSpeedCustomModel(avSpeedEnc). addToSpeed(If("true", LIMIT, "72"))).calcMinWeightPerDistance(), .001); // ignore too big limi...
public static boolean tryFillGap( final UnsafeBuffer logMetaDataBuffer, final UnsafeBuffer termBuffer, final int termId, final int gapOffset, final int gapLength) { int offset = (gapOffset + gapLength) - FRAME_ALIGNMENT; while (offset >= gapOffset) { ...
@Test void shouldNotOverwriteExistingFrame() { final int gapOffset = 0; final int gapLength = 64; dataFlyweight.frameLength(32); assertFalse(TermGapFiller.tryFillGap(metaDataBuffer, termBuffer, TERM_ID, gapOffset, gapLength)); }