focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public NormalDistStats scaleBy(double v) { double newMean = mean * v; double shiftAmount = newMean - mean; return new NormalDistStats(Math.max(0, mean + shiftAmount), stddev, Math.max(0, min + shiftAmount), Math.max(0, max + shiftAmount)); }
@Test public void scaleBy() { NormalDistStats orig = new NormalDistStats(1.0, 0.5, 0.0, 2.0); assertNDSEquals(orig, orig.scaleBy(1.0)); NormalDistStats expectedDouble = new NormalDistStats(2.0, 0.5, 1.0, 3.0); assertNDSEquals(expectedDouble, orig.scaleBy(2.0)); NormalDistStat...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { if(containerService.isContainer(folder)) { final S3BucketCreateService service = new S3BucketCreateService(session); service.create(folder, StringUtils.isBlank(status.getRegion())...
@Test public void testCreatePlaceholderVersioningDeleteWithMarker() throws Exception { final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); fi...
public void setMode(short mode) { mMode = mode; }
@Test public void setMode() { AccessControlList acl = new AccessControlList(); short mode = new Mode(Mode.Bits.EXECUTE, Mode.Bits.WRITE, Mode.Bits.READ).toShort(); acl.setMode(mode); assertEquals(mode, acl.getMode()); }
public static byte[] toByteArray(long value, int length) { final byte[] buffer = ByteBuffer.allocate(8).putLong(value).array(); for (int i = 0; i < 8 - length; i++) { if (buffer[i] != 0) { throw new IllegalArgumentException( "Value is does not fit into byt...
@Test public void toByteArrayBigIntegerShouldRemove() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Value is does not fit into byte array 9 > 8"); assertArrayEquals(new byte[] { 2 }, ByteArrayUtils.toByteArray(BigInteger.valueOf(0x102L), 1)); }
public void ipCheck(EidSession session, String clientIp) { if (session.getClientIpAddress() != null && !session.getClientIpAddress().isEmpty()) { String[] clientIps = clientIp.split(", "); byte[] data = clientIps[0].concat(sourceIpSalt).getBytes(StandardCharsets.UTF_8); Stri...
@Test public void testIpCheckCorrectIp() { setIpCheck(true); EidSession session = new EidSession(); session.setClientIpAddress("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); assertDoesNotThrow(() -> target.ipCheck(session, "SSSSSSSSSSSSSS")); }
@Override public Entry next(Entry reuse) throws IOException { // Ignore reuse, because each HeadStream has its own reuse BinaryRowData. return next(); }
@Test public void testMergeOfTenStreams() throws Exception { List<MutableObjectIterator<BinaryRowData>> iterators = new ArrayList<>(); iterators.add( newIterator(new int[] {1, 2, 17, 23, 23}, new String[] {"A", "B", "C", "D", "E"})); iterators.add( newIterator...
public void run(OutputReceiver<PartitionRecord> receiver) throws InvalidProtocolBufferException { // Erase any existing missing partitions. metadataTableDao.writeDetectNewPartitionMissingPartitions(new HashMap<>()); List<PartitionRecord> partitions = metadataTableDao.readAllStreamPartitions(); for (Pa...
@Test public void testOutputExistingStreamPartitions() throws InvalidProtocolBufferException { ByteStringRange partition1 = ByteStringRange.create("A", "B"); Instant watermark1 = Instant.now().minus(Duration.standardSeconds(10)); PartitionRecord partitionWithStartTime = new PartitionRecord(partiti...
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testMaxAllocationsPerAMHeartbeatDifferentSchedKey() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); allocator.setMaxAllocationsPerAMHeartbeat(2); final ExecutionTypeReque...
public void removeProblemsOfType(String type) { removeIf(problem -> type.equals(problem.type)); }
@Test void testRemoveProblemsOfType() { problems.addProblem(new CpuAllocationIrregularityProblem(new ArrayList<>())); assertThat(problems).hasSize(1); problems.removeProblemsOfType(CpuAllocationIrregularityProblem.PROBLEM_TYPE); assertThat(problems).isEmpty(); }
@Override public ObjectNode encode(MaintenanceDomain md, CodecContext context) { checkNotNull(md, "Maintenance Domain cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(MD_NAME, md.mdId().toString()) .put(MD_NAME_TYPE, md.mdId().nameType()....
@Test public void testEncodeMd2() throws CfmConfigException { MaintenanceDomain md2 = DefaultMaintenanceDomain.builder(MDID2_DOMAIN) .mdLevel(MaintenanceDomain.MdLevel.LEVEL2).build(); ObjectNode node = mapper.createObjectNode(); node.set("md", context.codec(MaintenanceDomai...
protected CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageFromRemoteAsync(String topic, long offset, int queueId, String brokerName) { try { String brokerAddr = this.brokerController.getTopicRouteInfoManager().findBrokerAddressInSubscribe(brokerName, MixAll.MASTER_ID, false); ...
@Test public void getMessageFromRemoteAsyncTest_message_notFound() throws Exception { PullResult pullResult = new PullResult(PullStatus.NO_MATCHED_MSG, 1, 1, 1, null); when(brokerOuterAPI.pullMessageFromSpecificBrokerAsync(anyString(), anyString(), anyString(), anyString(), anyInt(), anyLong(), anyI...
public static byte[] toBytes(String input) { if (input == null) { return EMPTY; } return input.getBytes(StandardCharsets.UTF_8); }
@Test void stringToByte() { byte[] bytes = ByteUtils.toBytes("google"); assertNotNull(bytes); }
public Group getGroup(JID jid) throws GroupNotFoundException { JID groupJID = GroupJID.fromJID(jid); return (groupJID instanceof GroupJID) ? getGroup(((GroupJID)groupJID).getGroupName()) : null; }
@Test public void willUseACacheHit() throws Exception { groupCache.put(GROUP_NAME, CacheableOptional.of(cachedGroup)); final Group returnedGroup = groupManager.getGroup(GROUP_NAME, false); assertThat(returnedGroup, is(cachedGroup)); verifyNoMoreInteractions(groupProvider); }
@Override public GrokPattern save(GrokPattern pattern) throws ValidationException { try { if (!validate(pattern)) { throw new ValidationException("Pattern " + pattern.name() + " invalid."); } } catch (GrokException | PatternSyntaxException e) { thr...
@Test public void save() throws Exception { // new pattern final GrokPattern pattern = service.save(GrokPattern.create("NEW", ".*")); assertThat(pattern).isNotNull(); assertThat(pattern.id()).isNotEmpty(); // check that updating works final GrokPattern updated = ser...
public static String format(double amount, boolean isUseTraditional) { return format(amount, isUseTraditional, false); }
@Test public void formatTraditionalTest() { String f1 = NumberChineseFormatter.format(10889.72356, true); assertEquals("壹万零捌佰捌拾玖点柒贰", f1); f1 = NumberChineseFormatter.format(12653, true); assertEquals("壹万贰仟陆佰伍拾叁", f1); f1 = NumberChineseFormatter.format(215.6387, true); assertEquals("贰佰壹拾伍点陆肆", f1); f1 =...
public void write(final ConsumerRecord<byte[], byte[]> record) throws IOException { if (!writable) { throw new IOException("Write permission denied."); } final File dirty = dirty(file); final File tmp = tmp(file); // first write to the dirty copy appendRecordToFile(record, dirty, filesyste...
@Test public void shouldWriteRecord() throws IOException { // Given final ConsumerRecord<byte[], byte[]> record = newStreamRecord("stream1"); // When replayFile.write(record); // Then final List<String> commands = Files.readAllLines(internalReplayFile.toPath()); assertThat(commands.size(...
@Override public Object getServiceDetail(String namespaceId, String groupName, String serviceName) throws NacosException { Service service = Service.newService(namespaceId, groupName, serviceName); if (!ServiceManager.getInstance().containSingleton(service)) { throw new NacosException(Na...
@Test void testGetServiceDetailNonExist() throws NacosException { assertThrows(NacosException.class, () -> { catalogServiceV2Impl.getServiceDetail("A", "BB", "CC"); }); }
@Override public Long createFileConfig(FileConfigSaveReqVO createReqVO) { FileConfigDO fileConfig = FileConfigConvert.INSTANCE.convert(createReqVO) .setConfig(parseClientConfig(createReqVO.getStorage(), createReqVO.getConfig())) .setMaster(false); // 默认非 master fileCo...
@Test public void testCreateFileConfig_success() { // 准备参数 Map<String, Object> config = MapUtil.<String, Object>builder().put("basePath", "/yunai") .put("domain", "https://www.iocoder.cn").build(); FileConfigSaveReqVO reqVO = randomPojo(FileConfigSaveReqVO.class, ...
public Set<String> filesInDirectory(File dir) throws IOException { Set<String> fileList = new HashSet<>(); Path dirPath = Paths.get(dir.getPath()); if (!Files.exists(dirPath)) { return Collections.emptySet(); } try (DirectoryStream<Path> stream = Files.newDirectoryS...
@Test public void testFilesInDirectory() throws IOException { String content = "x y z"; Path path = Paths.get(temporaryDirectory.getPath(), FOOBAR); File letters = path.toFile(); Files.write(letters.toPath(), Collections.singletonList(content)); path = Paths.get(temporaryDi...
public static Optional<Expression> convert( org.apache.flink.table.expressions.Expression flinkExpression) { if (!(flinkExpression instanceof CallExpression)) { return Optional.empty(); } CallExpression call = (CallExpression) flinkExpression; Operation op = FILTERS.get(call.getFunctionDefi...
@Test public void testEqualsNaN() { UnboundPredicate<Float> expected = org.apache.iceberg.expressions.Expressions.isNaN("field3"); Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert(resolve(Expressions.$("field3").isEqual(Expressions.lit(Float.NaN)))); assertThat(ac...
public Span nextSpan(Message message) { TraceContextOrSamplingFlags extracted = extractAndClearTraceIdProperties(processorExtractor, message, message); Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler. // When an upstream context was not present, lookup keys are unl...
@Test void nextSpan_should_tag_queue_when_no_incoming_context() throws JMSException { message.setJMSDestination(createDestination("foo", TYPE.QUEUE)); jmsTracing.nextSpan(message).start().finish(); assertThat(testSpanHandler.takeLocalSpan().tags()) .containsOnly(entry("jms.queue", "foo")); }
@POST @Path("/generate_regex") @Timed @ApiOperation(value = "Generates a regex that can be used as a value for a whitelist entry.") @NoAuditEvent("Utility function only.") @Consumes(MediaType.APPLICATION_JSON) public WhitelistRegexGenerationResponse generateRegex(@ApiParam(name = "JSON body", re...
@Test public void generateRegexForTemplate() { final WhitelistRegexGenerationRequest request = WhitelistRegexGenerationRequest.create("https://example.com/api/lookup?key=${key}", "${key}"); final WhitelistRegexGenerationResponse response = urlWhitelistResource.generateRegex(request);...
@PostMapping(value = "/localCache") @Secured(resource = Constants.OPS_CONTROLLER_PATH, action = ActionTypes.WRITE, signType = SignType.CONSOLE) public String updateLocalCacheFromStore() { LOGGER.info("start to dump all data from store."); dumpService.dumpAll(); LOGGER.info("finish to dum...
@Test void testUpdateLocalCacheFromStore() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.OPS_CONTROLLER_PATH + "/localCache"); int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus(); assertEquals(200, actua...
@Override public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException { JCExpression expression = getExpression().inline(inliner); if (expression.toString().equals(CONVERT_TO_IDENT)) { return inliner.maker().Ident(getIdentifier().inline(inliner)); } // TODO(lowasser): consi...
@Test public void inline() { ULiteral fooLit = ULiteral.stringLit("foo"); UType type = mock(UType.class); UMemberSelect memberSelect = UMemberSelect.create(fooLit, "length", type); assertInlines("\"foo\".length", memberSelect); }
@Override public ImagesAndRegistryClient call() throws IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { EventHandlers eventHandlers = buildContext...
@Test public void testCall_ManifestList() throws InvalidImageReferenceException, IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { Mockit...
@Override public boolean addAggrConfigInfo(final String dataId, final String group, String tenant, final String datumId, String appName, final String content) { String appNameTmp = StringUtils.isBlank(appName) ? StringUtils.EMPTY : appName; String tenantTmp = StringUtils.isBlank(tenant) ...
@Test void testAddAggrConfigInfoOfEqualContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; String datumId = "datumId"; String appName = "appname1234"; String content = "content1234"; //mock query datumId and equa...
TrashPolicy getTrashPolicy() { return trashPolicy; }
@Test public void testPluggableTrash() throws IOException { Configuration conf = new Configuration(); // Test plugged TrashPolicy conf.setClass("fs.trash.classname", TestTrashPolicy.class, TrashPolicy.class); Trash trash = new Trash(conf); assertTrue(trash.getTrashPolicy().getClass().equals(TestT...
@Override protected CouchbaseEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { CouchbaseEndpoint endpoint = new CouchbaseEndpoint(uri, remaining, this); setProperties(endpoint, parameters); return endpoint; }
@Test public void testCouchbaseURI() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("bucket", "bucket"); String uri = "couchbase:http://localhost"; String remaining = "http://localhost"; CouchbaseEndpoint endpoint = new CouchbaseComponent(context...
@Override public CompletableFuture<StreamedQueryResult> continueFromLastContinuationToken() { if (!this.hasContinuationToken()) { throw new KsqlClientException( "Can only continue queries that have saved a continuation token."); } return this.client.streamQuery(sql, properties); }
@Test public void shouldThrowOnContinueIfNoContinuationToken() { // When final Exception e = assertThrows( KsqlClientException.class, () -> queryResult.continueFromLastContinuationToken().get() ); // Then assertThat(e.getMessage(), containsString("Can only continue queries that ha...
@Override public void run() { try { load(); if (!checkCompleted()) { GlobalExecutor.submitLoadDataTask(this, distroConfig.getLoadDataRetryDelayMillis()); } else { loadCallback.onSuccess(); Loggers.DISTRO.info("[DISTRO-INIT] ...
@Test void testRun() { distroLoadDataTask.run(); Map<String, Boolean> loadCompletedMap = (Map<String, Boolean>) ReflectionTestUtils.getField(distroLoadDataTask, "loadCompletedMap"); assertNotNull(loadCompletedMap); assertTrue(loadCompletedMap.containsKey(type)); verify(distro...
@Override @CacheEvict(cacheNames = RedisKeyConstants.OAUTH_CLIENT, allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 key,不好清理 public void deleteOAuth2Client(Long id) { // 校验存在 validateOAuth2ClientExists(id); // 删除 oauth2ClientMapper.deleteById(id); }
@Test public void testDeleteOAuth2Client_success() { // mock 数据 OAuth2ClientDO dbOAuth2Client = randomPojo(OAuth2ClientDO.class); oauth2ClientMapper.insert(dbOAuth2Client);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbOAuth2Client.getId(); // 调用 oauth2ClientServic...
public void init() throws ServerException { if (status != Status.UNDEF) { throw new IllegalStateException("Server already initialized"); } status = Status.BOOTING; verifyDir(homeDir); verifyDir(tempDir); Properties serverInfo = new Properties(); try { InputStream is = getResource...
@Test @TestException(exception = ServerException.class, msgRegExp = "S05.*") @TestDir public void siteFileNotAFile() throws Exception { String homeDir = TestDirHelper.getTestDir().getAbsolutePath(); File siteFile = new File(homeDir, "server-site.xml"); assertTrue(siteFile.mkdir()); Server server =...
@Override public final boolean add(E newElement) { if (newElement == null) { return false; } if (newElement.prev() != INVALID_INDEX || newElement.next() != INVALID_INDEX) { return false; } if ((size + 1) >= elements.length / 2) { changeCapa...
@Test public void testNullForbidden() { ImplicitLinkedHashMultiCollection<TestElement> multiColl = new ImplicitLinkedHashMultiCollection<>(); assertFalse(multiColl.add(null)); }
@Transactional(readOnly = true) public AuthFindDto.FindUsernameRes findUsername(String phone) { User user = readGeneralSignUpUser(phone); return AuthFindDto.FindUsernameRes.of(user); }
@DisplayName("휴대폰 번호를 통해 유저를 찾아 User를 반환한다.") @Test void findUsernameIfUserFound() { // given String phone = "010-1234-5678"; String username = "jayang"; User user = UserFixture.GENERAL_USER.toUser(); given(userService.readUserByPhone(phone)).willReturn(Optional.of(user))...
@Override public void onMsg(TbContext ctx, TbMsg msg) { locks.computeIfAbsent(msg.getOriginator(), SemaphoreWithTbMsgQueue::new) .addToQueueAndTryProcess(msg, ctx, this::processMsgAsync); }
@Test public void test_sqrt_5_default_value_failure() { var node = initNode(TbRuleNodeMathFunctionType.SQRT, new TbMathResult(TbMathArgumentType.TIME_SERIES, "result", 3, true, false, DataConstants.SERVER_SCOPE), new TbMathArgument(TbMathArgumentType.MESSAGE_BODY, "TestKey") ...
public static String preprocess(String literal) { if (literal == null) { return null; } StringBuilder sb = new StringBuilder(literal.length() - 2); for (int i = 1; i < literal.length() - 1; i++) { char ch = literal.charAt(i); if (ch == '\\') { if (i >= literal.length() - 2) {...
@Test(expected = IllegalArgumentException.class) public void preprocessWrongStr() { SelTypeUtil.preprocess("\"\\\""); }
public static String obfuscateCredentials(String originalUrl) { HttpUrl parsedUrl = HttpUrl.parse(originalUrl); if (parsedUrl != null) { return obfuscateCredentials(originalUrl, parsedUrl); } return originalUrl; }
@Test @UseDataProvider("obfuscateCredentialsUseCases") public void verify_obfuscateCredentials(String originalUrl, String expectedUrl) { assertThat(obfuscateCredentials(originalUrl, HttpUrl.parse(originalUrl))) .isEqualTo(obfuscateCredentials(originalUrl)) .isEqualTo(expectedUrl); }
@Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { writer.keyword("CREATE"); if (getReplace()) { writer.keyword("OR REPLACE"); } writer.keyword("EXTERNAL MAPPING"); if (ifNotExists) { writer.keyword("IF NOT EXISTS"); ...
@Test public void test_unparse_quoting() { Mapping mapping = new Mapping( "na\"me", "external\"name", null, "Type", null, singletonList(new MappingField("fi\"eld", QueryDataType.VARCHAR, "__key\"field")), ...
public static String decodeObjectIdentifier(byte[] data) { return decodeObjectIdentifier(data, 0, data.length); }
@Test public void decodeObjectIdentifierWithZeros() { assertEquals("0.1.0.2.0.3", Asn1Utils.decodeObjectIdentifier(new byte[] { 1, 0, 2, 0, 3 })); }
@VisibleForTesting static int getIdForInsertionRequest(EditorInfo info) { return info == null ? 0 : Arrays.hashCode(new int[] {info.fieldId, info.packageName.hashCode()}); }
@Test public void testQueueImageInsertionTillTargetTextBoxEntered() { Assert.assertEquals(0, ShadowToast.shownToastCount()); simulateFinishInputFlow(); EditorInfo info = createEditorInfoTextWithSuggestionsForSetUp(); EditorInfoCompat.setContentMimeTypes(info, new String[] {"image/gif"}); simulateO...
@Override public DeserializationHandlerResponse handle( final ProcessorContext context, final ConsumerRecord<byte[], byte[]> record, final Exception exception ) { log.debug( String.format("Exception caught during Deserialization, " + "taskId: %s, topic: %s, partition: %d, o...
@Test public void shouldCallErrorCollector() { when(record.topic()).thenReturn("test"); exceptionHandler.handle(context, record, mock(Exception.class)); verify(streamsErrorCollector).recordError("test"); }
public static boolean isProperClass(Class<?> clazz) { int mods = clazz.getModifiers(); return !(Modifier.isAbstract(mods) || Modifier.isInterface(mods) || Modifier.isNative(mods)); }
@Test void testClassIsNotProper() { assertThat(InstantiationUtil.isProperClass(Value.class)).isFalse(); }
@Override public void handleTenantInfo(TenantInfoHandler handler) { // 如果禁用,则不执行逻辑 if (isTenantDisable()) { return; } // 获得租户 TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId()); // 执行处理器 handler.handle(tenant); }
@Test public void testHandleTenantInfo_success() { // 准备参数 TenantInfoHandler handler = mock(TenantInfoHandler.class); // mock 未禁用 when(tenantProperties.getEnable()).thenReturn(true); // mock 租户 TenantDO dbTenant = randomPojo(TenantDO.class); tenantMapper.inser...
@GET @Path("/entity-uid/{uid}/") @Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8) public TimelineEntity getEntity( @Context HttpServletRequest req, @Context HttpServletResponse res, @PathParam("uid") String uId, @QueryParam("confstoretrieve") String confsToRetrieve, @Q...
@Test void testGetEntitiesWithLimit() throws Exception { Client client = createClient(); try { URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/" + "timeline/clusters/cluster1/apps/app1/entities/app?limit=2"); ClientResponse resp = getResponse(client, uri); Set<Timel...
public SortedSet<String> getNames() { return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); }
@Test public void hasASetOfHealthCheckNames() { assertThat(registry.getNames()).containsOnly("hc1", "hc2", "ahc"); }
public byte[] toByteArray() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { write(stream); } catch (IOException e) { // Should not happen as ByteArrayOutputStream does not throw IOException on write throw new RuntimeException(e); } ...
@Test public void testToByteArray_OP_PUSHDATA1() { // OP_PUSHDATA1 byte[] bytes = new byte[0xFF]; RANDOM.nextBytes(bytes); byte[] expected = ByteUtils.concat(new byte[] { OP_PUSHDATA1, (byte) 0xFF }, bytes); byte[] actual = new ScriptChunk(OP_PUSHDATA1, bytes).toByteArray(); ...
synchronized Object[] getOneRow( RowMetaInterface rowMeta, Object[] row ) throws KettleException { Object[] rowData = RowDataUtil.resizeArray( row, data.outputRowMeta.size() ); int index = 0; Set<Integer> numFieldsAlreadyBeenTransformed = new HashSet<Integer>(); for ( int i = 0; i < data.numFields; i++...
@Test public void testGetOneRow() throws Exception { ReplaceStringData data = new ReplaceStringData(); ReplaceString replaceString = new ReplaceString( stepMockHelper.stepMeta, data, 0, stepMockHelper.transMeta, stepMockHelper.trans ); RowMetaInterface inputRowMeta = new RowMeta(); inputRowMeta...
@VisibleForTesting public Path getAllocationFile(Configuration conf) throws UnsupportedFileSystemException { String allocFilePath = conf.get(FairSchedulerConfiguration.ALLOCATION_FILE, FairSchedulerConfiguration.DEFAULT_ALLOCATION_FILE); Path allocPath = new Path(allocFilePath); String alloc...
@Test (expected = UnsupportedFileSystemException.class) public void testDenyGetAllocationFileFromUnsupportedFileSystem() throws UnsupportedFileSystemException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, "badfs:///badfile"); AllocationFileLoaderService allocLoader = new AllocationFileL...
public static JsonNode toJsonNode(Object datum) { if (datum == null) { return null; } try { TokenBuffer generator = new TokenBuffer(new ObjectMapper(), false); toJson(datum, generator); return new ObjectMapper().readTree(generator.asParser()); } catch (IOException e) { thro...
@Test void testToJsonNode() { assertNull(toJsonNode(null)); assertEquals(NullNode.getInstance(), toJsonNode(JsonProperties.NULL_VALUE)); assertEquals(BooleanNode.TRUE, toJsonNode(true)); assertEquals(IntNode.valueOf(1), toJsonNode(1)); assertEquals(LongNode.valueOf(2), toJsonNode(2L)); assertE...
@Private @InterfaceStability.Unstable public static NodeId toNodeIdWithDefaultPort(String nodeIdStr) { if (nodeIdStr.indexOf(":") < 0) { return NodeId.fromString(nodeIdStr + ":0"); } return NodeId.fromString(nodeIdStr); }
@Test void testNodeIdWithDefaultPort() throws URISyntaxException { NodeId nid; nid = ConverterUtils.toNodeIdWithDefaultPort("node:10"); assertThat(nid.getPort()).isEqualTo(10); assertThat(nid.getHost()).isEqualTo("node"); nid = ConverterUtils.toNodeIdWithDefaultPort("node"); assertThat(nid.g...
Optional<String> getFromDiscretizeBins(Number toEvaluate) { return discretizeBins .stream() .map(kiePMMLNameValue -> kiePMMLNameValue.evaluate(toEvaluate)) .filter(Optional::isPresent) .findFirst() .map(Optional::get); }
@Test void getFromDiscretizeBins() { KiePMMLDiscretize kiePMMLDiscretize = getKiePMMLDiscretize(null, null); Optional<String> retrieved = kiePMMLDiscretize.getFromDiscretizeBins(10); assertThat(retrieved).isPresent(); retrieved = kiePMMLDiscretize.getFromDiscretizeBins(20); a...
public static void addCurSizeAllMemTables(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, ...
@Test public void shouldAddCurSizeAllMemTablesMetric() { final String name = "cur-size-all-mem-tables"; final String description = "Approximate size of active and unflushed immutable memtables in bytes"; runAndVerifyMutableMetric( name, description, () -> ...
public static String getSystemProperty(String key) { String value = System.getenv(key); if (StringUtils.isEmpty(value)) { value = System.getProperty(key); } return value; }
@Test void testGetSystemProperty() throws Exception { try { System.setProperty("dubbo", "system-only"); assertThat(ConfigUtils.getSystemProperty("dubbo"), equalTo("system-only")); } finally { System.clearProperty("dubbo"); } }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Activity activity = (Activity) o; return Objects.equals(caller, activity.caller) && Objects.equals(...
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(Activity.class) .suppress(Warning.NONFINAL_FIELDS) .verify(); }
@Bean public ShenyuContextDecorator springCloudShenyuContextDecorator() { return new SpringCloudShenyuContextDecorator(); }
@Test public void testSpringCloudShenyuContextDecorator() { applicationContextRunner.run(context -> { ShenyuContextDecorator decorator = context.getBean("springCloudShenyuContextDecorator", ShenyuContextDecorator.class); assertNotNull(decorator); } ); ...
@Override public String createToken(Authentication authentication) throws AccessException { return getExecuteTokenManager().createToken(authentication); }
@Test void testCreateToken2() throws AccessException { assertEquals("token", tokenManagerDelegate.createToken("nacos")); }
@Override @PublicAPI(usage = ACCESS) public Set<JavaClass> getAllInvolvedRawTypes() { return Stream.of( Stream.of(this.returnType.get()), this.parameters.getParameterTypes().stream(), this.typeParameters.stream() ).flatMap(s -> s).map(JavaType::get...
@Test public void offers_all_involved_raw_types() { class SampleClass<T extends Collection<? super File> & Serializable> { @SuppressWarnings("unused") T method(List<Map<? extends Number, Set<? super String[][]>>> input) { return null; } } ...
@Override public Boolean authenticate(final Host bookmark, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("Login using none authentication with credentials %s", bookmark.getCredentials())); ...
@Test(expected = LoginFailureException.class) @Ignore public void testAuthenticate() throws Exception { assertFalse(new SFTPNoneAuthentication(session.getClient()).authenticate(session.getHost(), new DisabledLoginCallback(), new DisabledCancelCallback())); }
public RowMetaInterface getStepFields( String stepname ) throws KettleStepException { StepMeta stepMeta = findStep( stepname ); if ( stepMeta != null ) { return getStepFields( stepMeta ); } else { return null; } }
@Test public void infoStepFieldsAreNotIncludedInGetStepFields() throws KettleStepException { // validates that the fields from info steps are not included in the resulting step fields for a stepMeta. // This is important with steps like StreamLookup and Append, where the previous steps may or may not // ...
@Override public UrlPattern doGetPattern() { return UrlPattern.builder() .includes(includeUrls) .excludes(excludeUrls) .build(); }
@Test public void does_not_match_web_services_using_servlet_filter() { initWebServiceEngine(newWsUrl("api/authentication", "login").setHandler(ServletFilterHandler.INSTANCE)); assertThat(underTest.doGetPattern().matches("/api/authentication/login")).isFalse(); }
public List<GrantDTO> getForTargetExcludingGrantee(GRN target, GRN grantee) { return db.find(DBQuery.and( DBQuery.is(GrantDTO.FIELD_TARGET, target.toString()), DBQuery.notEquals(GrantDTO.FIELD_GRANTEE, grantee.toString()) )).toArray(); }
@Test @MongoDBFixtures("grants.json") public void getForTargetExcludingGrantee() { final GRN stream = grnRegistry.parse("grn::::stream:54e3deadbeefdeadbeef0001"); final GRN grantee = grnRegistry.parse("grn::::user:john"); assertThat(dbService.getForTargetExcludingGrantee(stream, grantee...
@Override public V load(K key) { awaitSuccessfulInit(); try (SqlResult queryResult = sqlService.execute(queries.load(), key)) { Iterator<SqlRow> it = queryResult.iterator(); V value = null; if (it.hasNext()) { SqlRow sqlRow = it.next(); ...
@Test public void givenTable_whenSetColumns_thenGenericRecordHasSetColumns() { ObjectSpec spec = new ObjectSpec(mapName, col("id", INT), col("name", STRING), col("age", INT), col("address", STRING)); objectProvider.createObject(spec); ...
@Override public void symlink(final Path file, String target) throws BackgroundException { try { session.sftp().symlink(target, file.getAbsolute()); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Cannot create {0}", e, file); } }
@Test public void testSymlink() throws Exception { final SFTPHomeDirectoryService workdir = new SFTPHomeDirectoryService(session); final Path target = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new SFTPTouchFeature(session).touch(target, new TransferS...
@Override public int hashCode() { return Objects.hash(super.hashCode(), firstChunkMsgId.hashCode()); }
@Test public void hashCodeTest() { ChunkMessageIdImpl chunkMsgId1 = new ChunkMessageIdImpl( new MessageIdImpl(0, 0, 0), new MessageIdImpl(1, 1, 1) ); ChunkMessageIdImpl chunkMsgId2 = new ChunkMessageIdImpl( new MessageIdImpl(2, 2, 2), ...
@Override public SQLRecognizer getSelectForUpdateRecognizer(String sql, SQLStatement ast) { if (((SQLSelectStatement) ast).getSelect().getFirstQueryBlock().isForUpdate()) { return new PolarDBXSelectForUpdateRecognizer(sql, ast); } return null; }
@Test public void getSelectForUpdateTest() { // common select without lock String sql = "SELECT name FROM t1 WHERE id = 1"; SQLStatement sqlStatement = getSQLStatement(sql); Assertions.assertNull(new PolarDBXOperateRecognizerHolder().getSelectForUpdateRecognizer(sql, sqlStatement)); ...
@ExceptionHandler(DuplicateKeyException.class) protected ShenyuAdminResult handleDuplicateKeyException(final DuplicateKeyException exception) { LOG.error("duplicate key exception ", exception); return ShenyuAdminResult.error(ShenyuResultMessage.UNIQUE_INDEX_CONFLICT_ERROR); }
@Test public void testServerExceptionHandlerByDuplicateKeyException() { DuplicateKeyException duplicateKeyException = new DuplicateKeyException("Test duplicateKeyException message!"); ShenyuAdminResult result = exceptionHandlersUnderTest.handleDuplicateKeyException(duplicateKeyException); As...
@Override public void run() throws Exception { //init all file systems List<PinotFSSpec> pinotFSSpecs = _spec.getPinotFSSpecs(); for (PinotFSSpec pinotFSSpec : pinotFSSpecs) { PinotFSFactory.register(pinotFSSpec.getScheme(), pinotFSSpec.getClassName(), new PinotConfiguration(pinotFSSpec)); ...
@Test public void testInputFilesWithSameNameInDifferentDirectories() throws Exception { File testDir = Files.createTempDirectory("testSegmentGeneration-").toFile(); testDir.delete(); testDir.mkdirs(); File inputDir = new File(testDir, "input"); File inputSubDir1 = new File(inputDir, "2009")...
@Udf public Long round(@UdfParameter final long val) { return val; }
@Test public void shouldRoundSimpleDoubleNegative() { assertThat(udf.round(-1.23d), is(-1L)); assertThat(udf.round(-1.0d), is(-1L)); assertThat(udf.round(-1.5d), is(-1L)); assertThat(udf.round(-1.75d), is(-2L)); assertThat(udf.round(-1.53e6d), is(-1530000L)); assertThat(udf.round(-10.01d), is(...
@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 static void readFullyOrFail(FileChannel channel, ByteBuffer destinationBuffer, long position, String description) throws IOException { if (position < 0) { throw new IllegalArgumentException("The file channel position cannot be negative, but it is " + pos...
@Test public void testReadFullyOrFailWithRealFile() throws IOException { try (FileChannel channel = FileChannel.open(TestUtils.tempFile().toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)) { // prepare channel String msg = "hello, world"; channel.write(ByteBuff...
public BootstrapMetadata read() throws Exception { Path path = Paths.get(directoryPath); if (!Files.isDirectory(path)) { if (Files.exists(path)) { throw new RuntimeException("Path " + directoryPath + " exists, but is not " + "a directory."); ...
@Test public void testReadFromConfigurationWithAncientVersion() throws Exception { try (BootstrapTestDirectory testDirectory = new BootstrapTestDirectory().createDirectory()) { assertEquals(BootstrapMetadata.fromVersion(MetadataVersion.MINIMUM_BOOTSTRAP_VERSION, "the minimum ...
@Override public String setOnu(String target) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId(); ...
@Test public void testValidSetOnu() throws Exception { String target; String reply; for (int i = ZERO; i < VALID_SET_TCS.length; i++) { target = VALID_SET_TCS[i]; currentKey = i; reply = voltConfig.setOnu(target); assertNotNull("Incorrect resp...
public static Messages getInstance() { return instance; }
@Test public void testEncoding() { assertEquals( "Wrong message returned", "", Messages.getInstance().getEncodedString( null ) ); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals( "Wrong message returned", "test: &#x81; &#x99;", Messages.getInstance().getXslString( "test.encode1" ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$...
@GetMapping("/by-namespace") public PageDTO<InstanceDTO> getInstancesByNamespace( @RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName, @RequestParam(value = "instanceAppId", required = false) String instanceAppId, ...
@Test public void testGetInstancesByNamespaceAndInstanceAppId() throws Exception { String someInstanceAppId = "someInstanceAppId"; String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; String someIp = "someIp"; long someInst...
@Override public <R extends MessageResponse<?>> void chatStream(Prompt<R> prompt, StreamResponseListener<R> listener, ChatOptions options) { LlmClient llmClient = new SseClient(); Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers....
@Test public void testChatStream() throws InterruptedException { OllamaLlmConfig config = new OllamaLlmConfig(); config.setEndpoint("http://localhost:11434"); config.setModel("llama3"); config.setDebug(true); Llm llm = new OllamaLlm(config); llm.chatStream("who are y...
@DELETE @Path("{networkId}/devices/{deviceId}") public Response removeVirtualDevice(@PathParam("networkId") long networkId, @PathParam("deviceId") String deviceId) { NetworkId nid = NetworkId.networkId(networkId); DeviceId did = DeviceId.deviceId(deviceId)...
@Test public void testDeleteVirtualDevice() { NetworkId networkId = networkId3; DeviceId deviceId = devId2; mockVnetAdminService.removeVirtualDevice(networkId, deviceId); expectLastCall(); replay(mockVnetAdminService); WebTarget wt = target() .propert...
public static <K, V> Read<K, V> read() { return new AutoValue_CdapIO_Read.Builder<K, V>().build(); }
@Test public void testReadExpandingFailsMissingCdapPluginClass() { PBegin testPBegin = PBegin.in(TestPipeline.create()); CdapIO.Read<String, String> read = CdapIO.read(); assertThrows(IllegalStateException.class, () -> read.expand(testPBegin)); }
public static boolean checkUserInfo( IUser user ) { return !StringUtils.isBlank( user.getLogin() ) && !StringUtils.isBlank( user.getName() ); }
@Test public void checkUserInfo_LoginIsNull() { assertFalse( RepositoryCommonValidations.checkUserInfo( user( null, "name" ) ) ); }
@Nullable static String method(Invocation invocation) { String methodName = invocation.getMethodName(); if ("$invoke".equals(methodName) || "$invokeAsync".equals(methodName)) { Object[] arguments = invocation.getArguments(); if (arguments != null && arguments.length > 0 && arguments[0] instanceof St...
@Test void method_invoke() { when(invocation.getMethodName()).thenReturn("$invoke"); when(invocation.getArguments()).thenReturn(new Object[] {"sayHello"}); assertThat(DubboParser.method(invocation)) .isEqualTo("sayHello"); }
public static String getGroupFromServiceName(String group) { return group; }
@Test public void testGetGroupFromServiceName() { String tempGroup = ConsulUtils.getGroupFromServiceName(testServiceName); assertEquals(testGroup, tempGroup); }
public synchronized @Nullable WorkItemServiceState reportUpdate( @Nullable DynamicSplitResult dynamicSplitResult, Duration requestedLeaseDuration) throws Exception { checkState(worker != null, "setWorker should be called before reportUpdate"); checkState(!finalStateSent, "cannot reportUpdates after ...
@Test public void reportUpdateBeforeSetWorker() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("setWorker"); thrown.expectMessage("reportUpdate"); statusClient.reportUpdate(null, null); }
public static KernelPlugin createFromObject(Object target, String pluginName) { Class<?> clazz = target.getClass(); return KernelPluginFactory.createFromObject(clazz, target, pluginName); }
@Test public void createFromObjectTest() { KernelPlugin plugin = KernelPluginFactory.createFromObject( new TestPlugin(), "test"); Assertions.assertNotNull(plugin); Assertions.assertEquals(plugin.getName(), "test"); Assertions.assertEquals(plugin.getFunctions(...
@Override public Publisher<Exchange> from(String uri) { final String name = publishedUriToStream.computeIfAbsent(uri, camelUri -> { try { String uuid = context.getUuidGenerator().generateUuid(); RouteBuilder.addRoutes(context, rb -> rb.from(camelUri).to("reactive...
@Test public void testFrom() throws Exception { context.start(); Publisher<Exchange> timer = crs.from("timer:reactive?period=250&repeatCount=3&includeMetadata=true"); AtomicInteger value = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(3); Flowable.fromPubl...
@SuppressWarnings("unchecked") public static <T> AgentServiceLoader<T> getServiceLoader(final Class<T> service) { return (AgentServiceLoader<T>) LOADERS.computeIfAbsent(service, AgentServiceLoader::new); }
@Test void assertGetServiceLoaderWithNoInterface() { assertThrows(IllegalArgumentException.class, () -> AgentServiceLoader.getServiceLoader(Object.class)); }
@Override public Set<CeWorker> getWorkers() { return ceWorkers; }
@Test public void getWorkers_returns_empty_if_create_has_not_been_called_before() { assertThat(underTest.getWorkers()).isEmpty(); }
@Override public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback) { Mono<T> toReturn = toRun.transform(new SentinelReactorTransformer<>( new EntryConfig(resourceName, entryType))); if (fallback != null) { toReturn = toReturn.onErrorResume(fallback); } return toReturn; }
@Test public void runMonoWithFallback() { ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() .create("foo"); assertThat(Mono.error(new RuntimeException("boom")) .transform(it -> cb.run(it, t -> Mono.just("fallback"))).block()) .isEqualTo("fallback"); }
public void validatePositionsIfNeeded() { Map<TopicPartition, SubscriptionState.FetchPosition> partitionsToValidate = offsetFetcherUtils.getPartitionsToValidate(); validatePositionsAsync(partitionsToValidate); }
@Test public void testOffsetValidationFencing() { buildFetcher(); assignFromUser(singleton(tp0)); Map<String, Integer> partitionCounts = new HashMap<>(); partitionCounts.put(tp0.topic(), 4); final int epochOne = 1; final int epochTwo = 2; final int epochThre...
public static ClusterOperatorConfig buildFromMap(Map<String, String> map) { warningsForRemovedEndVars(map); KafkaVersion.Lookup lookup = parseKafkaVersions(map.get(STRIMZI_KAFKA_IMAGES), map.get(STRIMZI_KAFKA_CONNECT_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER_IMAGES), map.get(STRIMZI_KAFKA_MIRROR_MAKER...
@Test public void testImagePullSecretsThrowsWithUpperCaseCharacter() { Map<String, String> envVars = new HashMap<>(ClusterOperatorConfigTest.ENV_VARS); envVars.put(ClusterOperatorConfig.IMAGE_PULL_SECRETS.key(), "Secret"); assertThrows(InvalidConfigurationException.class, () -> ...
@VisibleForTesting static <T> List<T> topologicalSort(Graph<T> graph) { MutableGraph<T> graphCopy = Graphs.copyOf(graph); List<T> l = new ArrayList<>(); Set<T> s = graphCopy.nodes().stream() .filter(node -> graphCopy.inDegree(node) == 0) .collect(Collectors.toSet()); while (!s.isEmpty()) { Iterator...
@Test public void testTopologicalSort() { MutableGraph<Integer> graph = GraphBuilder .directed() .build(); graph.addNode(1); graph.addNode(2); graph.addNode(3); graph.putEdge(1, 2); graph.putEdge(1, 3); List<Integer> sorted = PluginManager.topologicalSort(graph); assertTrue(sorted.indexOf(1)...
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) { return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive(); }
@Test public void tree() { // 0 - 1 - 2 - 4 - 5 // | \- 6 - 7 // 3 \- 8 g.edge(0, 1).setDistance(1).set(speedEnc, 10, 10); g.edge(1, 2).setDistance(1).set(speedEnc, 10, 10); g.edge(1, 3).setDistance(1).set(speedEnc, 10, 10); g.edge(2, 4).setD...
public static String stripTillLastOccurrenceOf(String input, String pattern) { if (!StringUtils.isBlank(input) && !StringUtils.isBlank(pattern)) { int index = input.lastIndexOf(pattern); if (index > 0) { input = input.substring(index + pattern.length()); } ...
@Test public void shouldStripTillLastOccurrenceOfGivenString() { assertThat(stripTillLastOccurrenceOf("HelloWorld@@\\nfoobar\\nquux@@keep_this", "@@"), is("keep_this")); assertThat(stripTillLastOccurrenceOf("HelloWorld", "@@"), is("HelloWorld")); assertThat(stripTillLastOccurrenceOf(null, "@...
@Override public void commandSucceeded(CommandSucceededEvent event) { Span span = threadLocalSpan.remove(); if (span == null) return; span.finish(); }
@Test void commandSucceeded_withoutCommandStarted() { listener.commandSucceeded(createCommandSucceededEvent()); verify(threadLocalSpan).remove(); verifyNoMoreInteractions(threadLocalSpan); }
public static TableRecords empty(TableMeta tableMeta) { return new EmptyTableRecords(tableMeta); }
@Test public void testEmpty() { TableRecords.EmptyTableRecords emptyTableRecords = new TableRecords.EmptyTableRecords(); Assertions.assertEquals(0, emptyTableRecords.size()); TableRecords empty = TableRecords.empty(new TableMeta()); Assertions.assertEquals(0, empty.size()); ...
void writeLogs(OutputStream out, Instant from, Instant to, long maxLines, Optional<String> hostname) { double fromSeconds = from.getEpochSecond() + from.getNano() / 1e9; double toSeconds = to.getEpochSecond() + to.getNano() / 1e9; long linesWritten = 0; BufferedWriter writer = new Buffer...
@Test void testThatLogsNotMatchingRegexAreExcluded() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*-1.*")); logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), 100, Optional.empty(...
@WithSpan @Override public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse result, Aggregations aggregations, ESGeneratedQueryContext queryContext) { final List<ResultMessageSummary> me...
@Test public void includesCustomNameInResultIfPresent() { final ESMessageList esMessageList = new ESMessageList(new LegacyDecoratorProcessor.Fake(), new TestResultMessageFactory(), false); final MessageList messageList = someMessageList().toBuilder().name("customResult").build(); ...
@Override public YamlShardingCacheConfiguration swapToYamlConfiguration(final ShardingCacheConfiguration data) { YamlShardingCacheConfiguration result = new YamlShardingCacheConfiguration(); result.setAllowedMaxSqlLength(data.getAllowedMaxSqlLength()); result.setRouteCache(cacheOptionsConfig...
@Test void assertSwapToYamlConfiguration() { YamlShardingCacheConfiguration actual = new YamlShardingCacheConfigurationSwapper() .swapToYamlConfiguration(new ShardingCacheConfiguration(100, new ShardingCacheOptionsConfiguration(true, 128, 1024))); assertThat(actual.getAllowedMaxSqlLe...
public RequestSpecification build() { return spec; }
@Test public void request_spec_picks_up_filters_from_static_config() { RestAssured.filters(new RequestLoggingFilter()); try { RequestSpecBuilder builder = new RequestSpecBuilder(); RequestSpecificationImpl spec = (RequestSpecificationImpl) builder.build(); Assert....
@Override public KCell[] getRow( int rownr ) { // xlsx raw row numbers are 1-based index, KSheet is 0-based // Don't check the upper limit as not all rows may have been read! // If it's found that the row does not exist, the exception will be thrown at the end of this method. if ( rownr < 0 ) { ...
@Test public void testInlineString() throws Exception { final String sheetId = "1"; final String sheetName = "Sheet 1"; XSSFReader reader = mockXSSFReader( sheetId, SHEET_INLINE_STRINGS, mock( SharedStringsTable.class ), mock( StylesTable.class ) ); StaxPoiSheet spSheet = new StaxPoiSheet(...
protected boolean shouldAnalyze() { if (analyzer instanceof FileTypeAnalyzer) { final FileTypeAnalyzer fileTypeAnalyzer = (FileTypeAnalyzer) analyzer; return fileTypeAnalyzer.accept(dependency.getActualFile()); } return true; }
@Test public void shouldAnalyzeReturnsTrueIfTheFileTypeAnalyzersAcceptsTheDependency() { final File dependencyFile = new File(""); new Expectations() {{ dependency.getActualFile(); result = dependencyFile; fileTypeAnalyzer.accept(dependencyFile); resu...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testStaleOutOfRangeError() { // verify that an out of range error which arrives after a seek // does not cause us to reset our position or throw an exception buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertEquals(1,...