focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Type type() { return type; }
@Test public void testTypeNotNull() { assertThrows(SchemaBuilderException.class, () -> SchemaBuilder.type(null)); }
static void clusterIdCommand(PrintStream stream, Admin adminClient) throws Exception { String clusterId = adminClient.describeCluster().clusterId().get(); if (clusterId != null) { stream.println("Cluster ID: " + clusterId); } else { stream.println("No cluster ID found. Th...
@Test public void testClusterTooOldToHaveId() throws Exception { Admin adminClient = new MockAdminClient.Builder(). clusterId(null). build(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ClusterTool.clusterIdCommand(new PrintStream(stream), admi...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final FileChannel channel = FileChannel.open(session.toPath(file), StandardOpenOption.READ); channel.position(status.getOffset()); ...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLogin...
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsExactly_primitiveDoubleArray_success() { assertThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsExactly(array(2.2, 1.1, 3.3)); }
@Override public void onCommitFailure(GlobalTransaction tx, Throwable cause) { LOGGER.warn("Failed to commit transaction[" + tx.getXid() + "]", cause); TIMER.newTimeout(new CheckTimerTask(tx, GlobalStatus.Committed), SCHEDULE_INTERVAL_SECONDS, TimeUnit.SECONDS); }
@Test void onCommitFailure() throws Exception{ RootContext.bind(DEFAULT_XID); GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate(); FailureHandler failureHandler = new DefaultFailureHandlerImpl(); failureHandler.onCommitFailure(tx, new MyRuntimeException("").getCause...
@Override public VirtualNetwork createVirtualNetwork(TenantId tenantId) { checkNotNull(tenantId, TENANT_NULL); return store.addNetwork(tenantId); }
@Test(expected = NullPointerException.class) public void testCreateNullVirtualNetwork() { manager.createVirtualNetwork(null); }
static boolean allowCodeRange(int prev, int next) { if ((prev + 1) != next) { return false; } int prevH = (prev >> 8) & 0xFF; int prevL = prev & 0xFF; int nextH = (next >> 8) & 0xFF; int nextL = next & 0xFF; return prevH == nextH && prevL ...
@Test void testAllowCodeRange() { // Denied progressions (negative) assertFalse(ToUnicodeWriter.allowCodeRange(0x000F, 0x0007)); assertFalse(ToUnicodeWriter.allowCodeRange(0x00FF, 0x0000)); assertFalse(ToUnicodeWriter.allowCodeRange(0x03FF, 0x0300)); assertFalse(ToUnicode...
@Override public int compareTo(DateTimeStamp dateTimeStamp) { return comparator.compare(this,dateTimeStamp); }
@Test void compareToTransitivity() { DateTimeStamp stamp1 = new DateTimeStamp("2021-09-01T11:12:13.111-0100", 100); DateTimeStamp stamp2 = new DateTimeStamp((String)null, 200); DateTimeStamp stamp3 = new DateTimeStamp("2021-08-31T11:12:13.111-0100", 300); assertTrue(stamp1.compareTo(...
public static Table getTableMeta(DataSource ds, String tableName) { return getTableMeta(ds, null, null, tableName); }
@Test public void getTableMetaTest() { final Table table = MetaUtil.getTableMeta(ds, "user"); assertEquals(CollectionUtil.newHashSet("id"), table.getPkNames()); }
@Override public void remove(NamedNode master) { connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName()); }
@Test public void testRemove() { Collection<RedisServer> masters = connection.masters(); connection.remove(masters.iterator().next()); }
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT); assert shenyuContext != null; DivideRuleHandle ruleHandle = bu...
@Test public void doPostExecuteTest() { when(chain.execute(postExchange)).thenReturn(Mono.empty()); Mono<Void> result = dividePlugin.doExecute(postExchange, chain, selectorData, ruleData); StepVerifier.create(result).expectSubscription().verifyComplete(); }
public final static Object getObject(String commandPart, Gateway gateway) { if (isEmpty(commandPart) || isEnd(commandPart)) { throw new Py4JException("Command Part is Empty or is the End of Command Part"); } else { switch (commandPart.charAt(0)) { case BOOLEAN_TYPE: return getBoolean(commandPart); c...
@Test public void testGetObject() { Gateway gateway = new Gateway(null); Object obj1 = new Object(); gateway.putObject("o123", obj1); assertEquals(1, Protocol.getObject("i1", null)); assertEquals(true, Protocol.getObject("bTrue", null)); assertEquals(1.234, (Double) Protocol.getObject("d1.234", null), 0.00...
public void recordOffset(TopicPartition partition, long partitionLastOffset) { lastProcessedOffset.put(partition, partitionLastOffset); }
@Order(1) @Test @DisplayName("Tests whether the cache can record offset a single offset") void updateOffsetsSinglePartition() { final TopicPartition topic1 = new TopicPartition("topic1", 1); assertDoesNotThrow(() -> offsetCache.recordOffset(topic1, 1)); assertDoesNotThrow(() -> offs...
public static <T> void maybeMergeOptions(Properties props, String key, OptionSet options, OptionSpec<T> spec) { if (options.has(spec) || !props.containsKey(key)) { T value = options.valueOf(spec); if (value == null) { props.remove(key); } else { ...
@Test public void testMaybeMergeOptionsDefaultValueIfNotExist() { setUpOptions(); OptionSet options = parser.parse(); CommandLineUtils.maybeMergeOptions(props, "skey", options, stringOpt); CommandLineUtils.maybeMergeOptions(props, "ikey", options, intOpt); CommandLineUtils....
@Override public int getOrder() { return PluginEnum.MODIFY_RESPONSE.getCode(); }
@Test public void testGetOrder() { assertEquals(modifyResponsePlugin.getOrder(), PluginEnum.MODIFY_RESPONSE.getCode()); }
@SuppressWarnings("unchecked") @Override public MoveApplicationAcrossQueuesResponse moveApplicationAcrossQueues( MoveApplicationAcrossQueuesRequest request) throws YarnException { ApplicationId applicationId = request.getApplicationId(); UserGroupInformation callerUGI = getCallerUgi(applicationId, ...
@Test public void testMoveApplicationSubmitTargetQueue() throws Exception { // move the application as the owner ApplicationId applicationId = getApplicationId(1); UserGroupInformation aclUGI = UserGroupInformation.getCurrentUser(); QueueACLsManager queueACLsManager = getQueueAclManager("allowed_queue...
@Override public List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException { return selectInstances(serviceName, new ArrayList<>(), healthy); }
@Test void testSelectInstancesWithHealthyFlag() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setHealthy(true); Instance instance1 = new Instance(); instance1.setHealthy(false); Instance instance2 = new In...
@Override public Type classify(final Throwable e) { final Type type = e instanceof MissingSourceTopicException ? Type.USER : Type.UNKNOWN; if (type == Type.USER) { LOG.info( "Classified error as USER error based on missing topic. Query ID: {} Exception: {}", queryId, e); ...
@Test public void shouldClassifyMissingTopicAsUserError() { // Given: final Exception e = new MissingSourceTopicException("foo"); // When: final Type type = new MissingTopicClassifier("").classify(e); // Then: assertThat(type, is(Type.USER)); }
public static CoordinatorRecord newConsumerGroupEpochTombstoneRecord( String groupId ) { return new CoordinatorRecord( new ApiMessageAndVersion( new ConsumerGroupMetadataKey() .setGroupId(groupId), (short) 3 ), n...
@Test public void testNewConsumerGroupEpochTombstoneRecord() { CoordinatorRecord expectedRecord = new CoordinatorRecord( new ApiMessageAndVersion( new ConsumerGroupMetadataKey() .setGroupId("group-id"), (short) 3), null); a...
@Override public PageResult<ProductBrandDO> getBrandPage(ProductBrandPageReqVO pageReqVO) { return brandMapper.selectPage(pageReqVO); }
@Test public void testGetBrandPage() { // mock 数据 ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class, o -> { // 等会查询到 o.setName("芋道源码"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCreateTime(buildTime(2022, 2, 1)); }); brandMapper.insert...
@Override public Long createMailTemplate(MailTemplateSaveReqVO createReqVO) { // 校验 code 是否唯一 validateCodeUnique(null, createReqVO.getCode()); // 插入 MailTemplateDO template = BeanUtils.toBean(createReqVO, MailTemplateDO.class) .setParams(parseTemplateContentParams(cr...
@Test public void testCreateMailTemplate_success() { // 准备参数 MailTemplateSaveReqVO reqVO = randomPojo(MailTemplateSaveReqVO.class) .setId(null); // 防止 id 被赋值 // 调用 Long mailTemplateId = mailTemplateService.createMailTemplate(reqVO); // 断言 assertNotNul...
public void handleSnapshot(MetadataImage image, KRaftMigrationOperationConsumer operationConsumer) { handleTopicsSnapshot(image.topics(), operationConsumer); handleConfigsSnapshot(image.configs(), operationConsumer); handleClientQuotasSnapshot(image.clientQuotas(), image.scram(), operationConsum...
@Test public void testExtraneousZkPartitions() { CapturingTopicMigrationClient topicClient = new CapturingTopicMigrationClient() { @Override public void iterateTopics(EnumSet<TopicVisitorInterest> interests, TopicVisitor visitor) { Map<Integer, List<Integer>> assignme...
@Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { log.debug("Resolving resource with systemId: {}", systemId); InputStream resourceStream = null; if (LOCAL_RESOLUTIONS.containsKey(systemId)) { log.debug("Got a lo...
@Test void testResolveResourceWithNonExistentResource() { String systemId = "non-existent.xsd"; LSInput lsInput = resolver.resolveResource(null, null, null, systemId, null); assertNull(lsInput); }
public void encode(final ByteBuf in, final ByteBuf out, final int length) { // Write the preamble length to the output buffer for (int i = 0;; i ++) { int b = length >>> i * 7; if ((b & 0xFFFFFF80) != 0) { out.writeByte(b & 0x7f | 0x80); } else { ...
@Test public void encodeShortTextIsLiteral() throws Exception { ByteBuf in = Unpooled.wrappedBuffer(new byte[] { 0x6e, 0x65, 0x74, 0x74, 0x79 }); ByteBuf out = Unpooled.buffer(7); snappy.encode(in, out, 5); ByteBuf expected = Unpooled.wrappedBuffer(new byte[] { ...
@Override public void remove(NamedNode master) { connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName()); }
@Test public void testRemove() { Collection<RedisServer> masters = connection.masters(); connection.remove(masters.iterator().next()); }
@Override public Set<String> getTopicClusterList( final String topic) throws InterruptedException, MQBrokerException, MQClientException, RemotingException { return this.defaultMQAdminExtImpl.getTopicClusterList(topic); }
@Test public void testGetTopicClusterList() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { Set<String> result = defaultMQAdminExt.getTopicClusterList("unit-test"); assertThat(result.size()).isEqualTo(0); }
public Result combine(Result other) { return new Result(this.isPass() && other.isPass(), this.isDescend() && other.isDescend()); }
@Test public void equalsPass() { Result one = Result.PASS; Result two = Result.PASS.combine(Result.PASS); assertEquals(one, two); }
static SearchProtocol.SearchRequest convertFromQuery(Query query, int hits, String serverId, double requestTimeout) { var builder = SearchProtocol.SearchRequest.newBuilder().setHits(hits).setOffset(query.getOffset()) .setTimeout((int) (requestTimeout * 1000)); var documentDb = query.get...
@Test void only_set_profiling_parameters_are_serialized_in_search_request() { var q = new Query("?query=test&trace.level=1&" + "trace.profiling.matching.depth=3"); var req = ProtobufSerialization.convertFromQuery(q, 1, "serverId", 0.5); assertEquals(3, req.getProfiling().getM...
public static void checkLiteralOverflowInBinaryStyle(BigDecimal value, ScalarType scalarType) throws AnalysisException { int realPrecision = getRealPrecision(value); int realScale = getRealScale(value); BigInteger underlyingInt = value.setScale(scalarType.getScalarScale(), RoundingMo...
@Test public void testCheckLiteralOverflowSuccess() throws AnalysisException { BigDecimal decimal32Values[] = { new BigDecimal("2147483.647"), new BigDecimal("2147483.6474"), new BigDecimal("2147483.6465"), new BigDecimal("2147483.0001"), ...
@PostMapping public ResponseEntity<Calificacion> guardarCalificacion (@RequestBody Calificacion calificacion) { return ResponseEntity.status(HttpStatus.CREATED).body(calificacionService.saveCalificacion(calificacion)); }
@Test void testGuardarCalificacion() throws Exception { when(calificacionService.saveCalificacion(ArgumentMatchers.any(Calificacion.class))).thenReturn(calificacion1); mockMvc.perform(post("/calificaciones") .contentType(MediaType.APPLICATION_JSON) .c...
public final Scheduler scheduler() { return scheduler; }
@Test public void test_scheduler() { Reactor reactor = newReactor(); assertNotNull(reactor.scheduler()); }
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { new SFTPAttributesFinderFeature(session).find(file, listener); return true; } catch(No...
@Test public void testFindDirectory() throws Exception { assertTrue(new SFTPFindFeature(session).find(new SFTPHomeDirectoryService(session).find())); }
@Override public void isNotEqualTo(@Nullable Object expected) { super.isNotEqualTo(expected); }
@Test public void isNotEqualTo_WithoutToleranceParameter_Success_NotAnArray() { assertThat(array(2.2f, 3.3f, 4.4f)).isNotEqualTo(new Object()); }
public static Integer getPort(String address) { Matcher matcher = HOST_PORT_PATTERN.matcher(address); return matcher.matches() ? Integer.parseInt(matcher.group(2)) : null; }
@Test public void testGetPort() { // valid assertEquals(8000, getPort("127.0.0.1:8000").intValue()); assertEquals(8080, getPort("mydomain.com:8080").intValue()); assertEquals(8080, getPort("MyDomain.com:8080").intValue()); assertEquals(1234, getPort("[::1]:1234").intValue());...
public static int isOctal(String str) { if (str == null || str.isEmpty()) { return -1; } return str.matches("[0-7]+") ? OCTAL_RADIX : -1; }
@Test public void isOctal_Test() { Assertions.assertEquals(8, TbUtils.isOctal("4567734")); Assertions.assertEquals(-1, TbUtils.isOctal("8100110")); }
public static boolean isEmail(String email) { return isMatch(EMAIL_REGEX, email); }
@Test public void testEmail() { Assert.assertEquals(false, PatternKit.isEmail("abcd")); Assert.assertEquals(true, PatternKit.isEmail("hellokaton@gmail.com")); Assert.assertEquals(true, PatternKit.isEmail("1234@q.com")); }
public static <T> PTransform<PCollection<T>, PCollection<KV<T, Long>>> perElement() { return new PerElement<>(); }
@Test @Category(NeedsRunner.class) @SuppressWarnings("unchecked") public void testCountPerElementEmpty() { PCollection<String> input = p.apply(Create.of(NO_LINES).withCoder(StringUtf8Coder.of())); PCollection<KV<String, Long>> output = input.apply(Count.perElement()); PAssert.that(output).empty(); ...
public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { final byte flags = header.flags(); if ((flags & UNFRAGMENTED) == UNFRAGMENTED) { delegate.onFragment(buffer, offset, length, header); } else { ...
@Test void shouldSkipOverMessagesWithLoss() { when(header.flags()) .thenReturn(FrameDescriptor.BEGIN_FRAG_FLAG) .thenReturn(FrameDescriptor.END_FRAG_FLAG) .thenReturn(FrameDescriptor.UNFRAGMENTED); final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[2048...
static void parseServerIpAndPort(MysqlConnection connection, Span span) { try { URI url = URI.create(connection.getURL().substring(5)); // strip "jdbc:" String remoteServiceName = connection.getProperties().getProperty("zipkinServiceName"); if (remoteServiceName == null || "".equals(remoteServiceN...
@Test void parseServerIpAndPort_ipFromHost_portFromUrl() throws SQLException { setupAndReturnPropertiesForHost("1.2.3.4"); TracingStatementInterceptor.parseServerIpAndPort(connection, span); verify(span).remoteServiceName("mysql"); verify(span).remoteIpAndPort("1.2.3.4", 5555); }
public Future<KafkaVersionChange> reconcile() { return getPods() .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testDowngradeWithUnsetDesiredMetadataVersion(VertxTestContext context) { VersionChangeCreator vcc = mockVersionChangeCreator( mockKafka(VERSIONS.version(KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION).version(), VERSIONS.version(KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION).m...
@Override protected ExecuteContext doBefore(ExecuteContext context) { if (!registerConfig.isOpenMigration() || RegisterDynamicConfig.INSTANCE.isNeedCloseOriginRegisterCenter()) { context.skip(null); } return context; }
@Test public void doBefore() throws NoSuchMethodException { registerConfig.setOpenMigration(true); final ExecuteContext context = interceptor .doBefore(ExecuteContext.forMemberMethod(this, String.class.getDeclaredMethod("trim"), null, null, null)); Ass...
public Distance lateralDistance() { return point1.latLong().distanceTo(point2.latLong()); }
@Test public void testLateralDistance() { Point p1 = Point.builder() .latLong(LatLong.of(0.0, 0.0)) .time(EPOCH) .build(); Point p2 = Point.builder() .latLong(p1.latLong().projectOut(0.0, 10.0)) //move 10 NM North .time(EPOCH) ...
@Override @Nullable public V put(@Nullable K key, @Nullable V value) { return put(key, value, true); }
@Test void shouldContainValue() { assertFalse(this.map.containsValue("123")); assertFalse(this.map.containsValue(null)); this.map.put(123, "123"); this.map.put(456, null); assertTrue(this.map.containsValue("123")); assertTrue(this.map.containsValue(null)); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.w...
@Test public void testMoveDirectory() throws Exception { final Path home = new DefaultHomeFinderService(session).find(); final Path directory = new DropboxDirectoryFeature(session).mkdir(new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStat...
@Override public void doRun() { final Instant mustBeOlderThan = Instant.now().minus(maximumSearchAge); searchDbService.getExpiredSearches(findReferencedSearchIds(), mustBeOlderThan).forEach(searchDbService::delete); }
@Test public void testForMixedReferencedNonReferencedExpiredAndNonexpiredSearches() { final ViewSummaryDTO view = ViewSummaryDTO.builder() .title("my-view") .searchId(IN_USE_SEARCH_ID) .build(); when(viewService.streamAll()).thenReturn(Stream.of(view)...
@Override protected URI getOrigin(final Path container, final Distribution.Method method) { final URI url = URI.create(String.format("%s%s", new DefaultWebUrlProvider().toUrl(origin).getUrl(), PathNormalizer.normalize(origin.getDefaultPath(), true))); if(log.isDebugEnabled()) { log.debug...
@Test public void testGetOrigin() { final Host origin = new Host(new TestProtocol(), "m"); final Path container = new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)); origin.setWebURL("http://w.example.net"); final CustomOriginCloudFrontDistributionConfiguration configur...
public static boolean columnEquals(Column base, Column other) { if (base == other) { return true; } if (!base.getName().equalsIgnoreCase(other.getName())) { return false; } if (!base.getType().equals(other.getType())) { return false; ...
@Test public void testColumnEquals() { Column base = new Column("k1", Type.INT, false); Column other = new Column("k1", Type.INT, false); Assert.assertTrue(columnEquals(base, base)); Assert.assertTrue(columnEquals(base, other)); other = new Column("k2", Type.INT, false); ...
@Override public Page download(Request request, Task task) { if (task == null || task.getSite() == null) { throw new NullPointerException("task or site can not be null"); } CloseableHttpResponse httpResponse = null; CloseableHttpClient httpClient = getHttpClient(task.getS...
@Test public void test_set_site_header() throws Exception { HttpServer server = httpServer(13423); server.get(eq(header("header"), "header-webmagic")).response("ok"); Runner.running(server, new Runnable() { @Override public void run() throws Exception { ...
public static PositionBound at(final Position position) { return new PositionBound(position); }
@Test public void shouldEqualSelf() { final PositionBound bound1 = PositionBound.at(Position.emptyPosition()); assertEquals(bound1, bound1); }
public static ReadAll readAll() { return new ReadAll(); }
@Test public void testReadAll() throws Exception { SolrIOTestUtils.insertTestDocuments(SOLR_COLLECTION, NUM_DOCS, solrClient); PCollection<SolrDocument> output = pipeline .apply( Create.of( SolrIO.read() .withConnectionConfigurat...
public ClassloaderBuilder newClassloader(String key) { return newClassloader(key, getSystemClassloader()); }
@Test public void fail_to_create_the_same_classloader_twice() throws Exception { sut.newClassloader("the-cl"); try { sut.newClassloader("the-cl"); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("The classloader 'the-cl' already exists. Can not create it twice."); ...
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@Test public void shouldNotAllowNullTableOnLeftJoinWithGlobalTableWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin( null, MockMapper.selectValueMapper(), MockValueJ...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { new SFTPAttributesFinderFeature(session).find(file, listener); return true; } catch(No...
@Test public void testFindNotFound() throws Exception { assertFalse(new SFTPFindFeature(session).find(new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)))); }
public static DaysWindows days(int number) { return new DaysWindows(number, DEFAULT_START_DATE, DateTimeZone.UTC); }
@Test public void testTimeZone() throws Exception { Map<IntervalWindow, Set<String>> expected = new HashMap<>(); DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles"); final List<Long> timestamps = Arrays.asList( new DateTime(2014, 1, 1, 0, 0, timeZone).getMillis(), ...
static void quoteExternalName(StringBuilder sb, String externalName) { List<String> parts = splitByNonQuotedDots(externalName); for (int i = 0; i < parts.size(); i++) { String unescaped = unescapeQuotes(parts.get(i)); String unquoted = unquoteIfQuoted(unescaped); DIAL...
@Test public void quoteExternalName_with_2dots() { String externalName = "catalog.custom_schema.my_table"; StringBuilder sb = new StringBuilder(); MappingHelper.quoteExternalName(sb, externalName); assertThat(sb.toString()).isEqualTo("\"catalog\".\"custom_schema\".\"my_table\""); ...
@Override public void bind() { thread.start(); }
@Test public void bind() throws IOException { ServerTakeHandler handler = new ServerTakeHandler(instance, o -> 1); ServerConnection connection = new SimpleServerConnection(handler); RPCServer rpcServer = new RPCServer(connection, RandomPort::getSafeRandomPort); rpcServer.bind(); ...
@Override public Iterable<T> get() { return values; }
@Test public void testGetCached() throws Exception { FakeBeamFnStateClient fakeBeamFnStateClient = new FakeBeamFnStateClient( StringUtf8Coder.of(), ImmutableMap.of(key(), asList("A1", "A2", "A3", "A4", "A5", "A6"))); Cache<?, ?> cache = Caches.eternal(); { // The fir...
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testJsonEmbeddedExpressionFailuresAreNotBlockers() { run( "def expected = { a: '#number', b: '#(_$.a * 2)' }", "def actual = [{a: 1, b: 2}, {a: 2, b: 4}]", "match each actual == expected" ); }
@SuppressWarnings("dereference.of.nullable") public static PTransform<PCollection<Failure>, PDone> getDlqTransform(String fullConfig) { List<String> strings = Splitter.on(":").limit(2).splitToList(fullConfig); checkArgument( strings.size() == 2, "Invalid config, must start with `identifier:`. %s", ful...
@Test public void testParseFailures() { assertThrows( IllegalArgumentException.class, () -> GenericDlq.getDlqTransform("no colon present")); assertThrows(IllegalArgumentException.class, () -> GenericDlq.getDlqTransform("bad_id:xxx")); assertThrows( IllegalArgumentException.class, (...
@Override public void deleteDiyPage(Long id) { // 校验存在 validateDiyPageExists(id); // 删除 diyPageMapper.deleteById(id); }
@Test public void testDeleteDiyPage_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> diyPageService.deleteDiyPage(id), DIY_PAGE_NOT_EXISTS); }
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseFromDeepinTest(){ // https://gitee.com/dromara/hutool/issues/I50YGY final String uaStr = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"; final UserAgent ua = UserAgentUtil.parse(uaStr); assertEquals("Linux", ua.getOs().toString...
@Override public List<PortStatistics> getPortStatistics(DeviceId deviceId) { checkNotNull(deviceId, DEVICE_NULL); // TODO not supported at the moment. return ImmutableList.of(); }
@Test(expected = NullPointerException.class) public void testGetPortsStatisticsByNullId() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); DeviceService deviceService = manager.get(...
public static int incrementSequence(int sequence, int increment) { if (sequence > Integer.MAX_VALUE - increment) return increment - (Integer.MAX_VALUE - sequence) - 1; return sequence + increment; }
@Test public void testIncrementSequence() { assertEquals(10, DefaultRecordBatch.incrementSequence(5, 5)); assertEquals(0, DefaultRecordBatch.incrementSequence(Integer.MAX_VALUE, 1)); assertEquals(4, DefaultRecordBatch.incrementSequence(Integer.MAX_VALUE - 5, 10)); }
@Cacheable("digid-app") public boolean digidAppSwitchEnabled(){ return isEnabled("Koppeling met DigiD app"); }
@Test void checkSwitchNotExisting() { var switchObject = createSwitch("other name", "Description van de switch A", SwitchStatus.ALL, 1, ZonedDateTime.now()); when(switchRepository.findByName("other name")).thenReturn(Optional.of(switchObject)); assertFalse(service.digidAppSwitchEnabled()); ...
@Override public String getName() { return LocaleFactory.localizedString("Amazon CloudFront", "S3"); }
@Test public void testGetName() { final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname())); final DistributionConfiguration configuration = new CloudFrontDistributionConfiguration( session, new S3LocationFeature(session), new DisabledX509...
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) { if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) { return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(), schemaDefinition.getSchema...
@Test public void testLogicalType() { AvroSchema<SchemaLogicalType> avroSchema = AvroSchema.of(SchemaDefinition.<SchemaLogicalType>builder() .withPojo(SchemaLogicalType.class).withJSR310ConversionEnabled(true).build()); SchemaLogicalType schemaLogicalType = new SchemaLogicalType(); ...
public void load() { if (fileHome == null || fileHome.isEmpty()) { return; } Map<String, Map<String, PlainAccessResource>> aclPlainAccessResourceMap = new HashMap<>(); Map<String, String> accessKeyTable = new HashMap<>(); List<RemoteAddressStrategy> globalWhiteRemote...
@Test public void loadTest() { plainPermissionManager.load(); final Map<String, DataVersion> map = plainPermissionManager.getDataVersionMap(); Assertions.assertThat(map).isNotEmpty(); }
public static <T> List<List<T>> split(List<T> list, int size) { return partition(list, size); }
@Test @Disabled public void splitBenchTest() { final List<String> list = new ArrayList<>(); CollUtil.padRight(list, RandomUtil.randomInt(1000_0000, 1_0000_0000), "test"); final int size = RandomUtil.randomInt(10, 1000); Console.log("\nlist size: {}", list.size()); Console.log("partition size: {}\n", size);...
@Override public double score(int[] truth, int[] prediction) { return of(truth, prediction, strategy); }
@Test public void test() { System.out.println("recall"); int[] truth = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
public static long elapsed(long started, long finished) { return Times.elapsed(started, finished, true); }
@Test void testNegativeStartandFinishTimes() { long elapsed = Times.elapsed(-5, -10, false); assertEquals(-1, elapsed, "Elapsed time is not -1"); }
@Override public void set(BitSet bs) { get(setAsync(bs)); }
@Test public void testSet() { RBitSet bs = redisson.getBitSet("testbitset"); assertThat(bs.set(3)).isFalse(); assertThat(bs.set(5)).isFalse(); assertThat(bs.set(5)).isTrue(); assertThat(bs.toString()).isEqualTo("{3, 5}"); BitSet bs1 = new BitSet(); bs1.set(1)...
@Override public final int available() { return size - pos; }
@Test public void testAvailable() { assertEquals(in.size - in.pos, in.available()); }
@Override public void startWatching() { if (settings.getProps().valueAsBoolean(ENABLE_STOP_COMMAND.getKey())) { super.startWatching(); } }
@Test public void startWatching_does_not_start_thread_if_stop_command_is_disabled() { TestAppSettings appSettings = new TestAppSettings(); StopRequestWatcherImpl underTest = new StopRequestWatcherImpl(appSettings, scheduler, commands); underTest.startWatching(); assertThat(underTest.isAlive()).isFals...
public static UUID createUuid(String input) { if (input == null) { return UUID.randomUUID(); } return UUID.nameUUIDFromBytes(input.getBytes(StandardCharsets.UTF_8)); }
@Test public void testCreateUuid() { String expected = "7b92bd31-8478-35db-bb77-dfdb3d7260fc"; Assert.assertEquals(expected, IdHelper.createUuid("test-uuid1").toString()); expected = "1e98c90b-0adf-3429-9a53-c8620d70fb5d"; Assert.assertEquals(expected, IdHelper.createUuid("test-uuid2").toString()); ...
ControllerResult<CreateTopicsResponseData> createTopics( ControllerRequestContext context, CreateTopicsRequestData request, Set<String> describable ) { Map<String, ApiError> topicErrors = new HashMap<>(); List<ApiMessageAndVersion> records = BoundedList.newArrayBacked(MAX_REC...
@Test public void testInvalidCreateTopicsWithValidateOnlyFlag() { ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().build(); ctx.registerBrokers(0, 1, 2); ctx.unfenceBrokers(0, 1, 2); CreateTopicsRequestData request = new CreateTopicsRequestData().setVal...
@Override protected double maintain() { if ( ! nodeRepository().nodes().isWorking()) return 0.0; // Don't need to maintain spare capacity in dynamically provisioned zones; can provision more on demand. if (nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0; NodeList ...
@Test public void testNoSpares() { var tester = new SpareCapacityMaintainerTester(); tester.addHosts(2, new NodeResources(10, 100, 1000, 1)); tester.addNodes(0, 2, new NodeResources(10, 100, 1000, 1), 0); tester.maintainer.maintain(); assertEquals(0, tester.deployer.activatio...
@Override public void calculate() { }
@Test public void testCalculate() { function.accept(MeterEntity.newService("service-test", Layer.GENERAL), SMALL_VALUE); function.accept(MeterEntity.newService("service-test", Layer.GENERAL), LARGE_VALUE); function.calculate(); assertThat(function.getValue()).isEqualTo(SMALL_VALUE);...
@Override public void transform(Message message, DataType fromType, DataType toType) { ProtobufSchema schema = message.getExchange().getProperty(SchemaHelper.CONTENT_SCHEMA, ProtobufSchema.class); if (schema == null) { throw new CamelExecutionException("Missing proper Protobuf schema fo...
@Test void shouldHandleJsonString() throws Exception { Exchange exchange = new DefaultExchange(camelContext); ProtobufSchema protobufSchema = getSchema(); exchange.setProperty(SchemaHelper.CONTENT_SCHEMA, protobufSchema); exchange.getMessage().setBody(""" { "name...
ClientConfigurationData createClientConfiguration() { ClientConfigurationData initialConf = new ClientConfigurationData(); ProxyConfiguration proxyConfig = service.getConfiguration(); initialConf.setServiceUrl( proxyConfig.isTlsEnabledWithBroker() ? service.getServiceUrlTls() : s...
@Test public void testCreateClientConfiguration() { ProxyConfiguration proxyConfiguration = new ProxyConfiguration(); proxyConfiguration.setTlsEnabledWithBroker(true); String proxyUrlTls = "pulsar+ssl://proxy:6651"; String proxyUrl = "pulsar://proxy:6650"; ProxyService proxy...
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldAllowHashCharacterInLabelTemplate() throws Exception { GoConfigHolder goConfigHolder = xmlLoader.loadConfigHolder(LABEL_TEMPLATE_WITH_LABEL_TEMPLATE("1.3.0-${COUNT}-${git}##")); assertThat(goConfigHolder.config.pipelineConfigByName(new CaseInsensitiveString("cruise")).getLabelTempla...
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void testExcludeObjectNames() throws Exception { JmxCollector jc = new JmxCollector( "\n---\nincludeObjectNames:\n- java.lang:*\n- org.apache.cassandra.concurrent:*\nexcludeObjectNames:\n- org.apache.cassandra.concurrent:*" ...
public List<Service> importServiceDefinition(String repositoryUrl, Secret repositorySecret, boolean disableSSLValidation, boolean mainArtifact) throws MockRepositoryImportException { log.info("Importing service definitions from {}", repositoryUrl); File localFile = null; Map<String, List<Stri...
@Test void testImportServiceDefinitionFromGitLabURL() { List<Service> services = null; try { services = service.importServiceDefinition( "https://gitlab.com/api/v4/projects/53583367/repository/files/complex-example%2Fopenapi.yaml/raw?head=main", null, true, true); ...
public void popNode() { current.finishSpecifying(); unexpandedInputs.remove(current); current = current.getEnclosingNode(); checkState(current != null, "Can't pop the root node of a TransformHierarchy"); }
@Test public void pushWithoutPushFails() { thrown.expect(IllegalStateException.class); hierarchy.popNode(); }
public File getUniqueFilenameForClass(String className) throws IOException { //class names should be passed in the normal dalvik style, with a leading L, a trailing ;, and using //'/' as a separator. if (className.charAt(0) != 'L' || className.charAt(className.length()-1) != ';') { t...
@Test public void testBasicFunctionality() throws IOException { File tempDir = Files.createTempDir().getCanonicalFile(); ClassFileNameHandler handler = new ClassFileNameHandler(tempDir, ".smali"); File file = handler.getUniqueFilenameForClass("La/b/c/d;"); checkFilename(tempDir, fil...
@Override public long add(double longitude, double latitude, V member) { return get(addAsync(longitude, latitude, member)); }
@Test public void testAdd() { RGeo<String> geo = redisson.getGeo("test"); assertThat(geo.add(2.51, 3.12, "city1")).isEqualTo(1); }
public byte[] getCompressedData() { return compressedData; }
@Test public void testGetCompressedData() { byte[] bytes = new byte[]{'h', 'e', 'l', 'l', 'o', '!'}; lz4CompressData.setCompressedData(bytes); Assertions.assertEquals(lz4CompressData.getCompressedData(), bytes); }
private Map<String, String> filterMdc(Map<String, String> mdcPropertyMap) { if (includesMdcKeys.isEmpty()) { return mdcPropertyMap; } return mdcPropertyMap.entrySet() .stream() .filter(e -> includesMdcKeys.contains(e.getKey())) .collect(Collectors....
@Test void testFilterMdc() { final Set<String> includesMdcKeys = Set.of("userId", "orderId"); Map<String, Object> map = new EventJsonLayout(jsonFormatter, timestampFormatter, throwableProxyConverter, DEFAULT_EVENT_ATTRIBUTES, Collections.emptyMap(), Collections.emptyMap(), includesMdcKey...
public static int getLevelForXp(int xp) { if (xp < 0) { throw new IllegalArgumentException("XP (" + xp + ") must not be negative"); } int low = 0; int high = XP_FOR_LEVEL.length - 1; while (low <= high) { int mid = low + (high - low) / 2; int xpForLevel = XP_FOR_LEVEL[mid]; if (xp < xpForL...
@Test(expected = IllegalArgumentException.class) public void testGetLevelForNegativeXP() { Experience.getLevelForXp(-1); }
private static void removeQueue( String queueToRemove, CapacitySchedulerConfiguration proposedConf, Map<String, String> confUpdate) throws IOException { if (queueToRemove == null) { return; } QueuePath queuePath = new QueuePath(queueToRemove); if (queuePath.isRoot() || queuePat...
@Test public void testRemoveQueue() throws Exception { SchedConfUpdateInfo updateInfo = new SchedConfUpdateInfo(); updateInfo.getRemoveQueueInfo().add(A_PATH); Map<String, String> configurationUpdate = ConfigurationUpdateAssembler.constructKeyValueConfUpdate(csConfig, updateInfo); 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( expected = ArrayIndexOutOfBoundsException.class ) public void testEmptySheet_row1() throws Exception { XSSFReader reader = mockXSSFReader( "sheet1", SHEET_EMPTY, mock( SharedStringsTable.class ), mock( StylesTable.class ) ); StaxPoiSheet sheet = new StaxPoiSheet( reader, "empty", "sheet1" ...
public String abbreviate(String fqClassName) { StringBuilder buf = new StringBuilder(targetLength); if (fqClassName == null) { throw new IllegalArgumentException("Class name may not be null"); } int inLen = fqClassName.length(); if (inLen < targetLength) { return fqClassName; } ...
@Test public void testTwoDot() { { TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); String name = "com.logback.Foobar"; assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); } { TargetLengthBasedClassNameAbbreviator abbreviator ...
public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException { Constructor<?> targetConstructor; try { targetConstructor = clazz.getConstructor(new Class<?>[] {paramType}); } catch (NoSuchMethodException e) { targetConstruc...
@Test void testFindConstructor() throws Exception { Constructor constructor = ReflectUtils.findConstructor(Foo3.class, Foo2.class); assertNotNull(constructor); }
public void applyConfig(ClientBwListDTO configDTO) { requireNonNull(configDTO, "Client filtering config must not be null"); requireNonNull(configDTO.mode, "Config mode must not be null"); requireNonNull(configDTO.entries, "Config entries must not be null"); ClientSelector selector; ...
@Test public void testApplyConfig_blacklist() { ClientBwListDTO config = createConfig(Mode.BLACKLIST, new ClientBwListEntryDTO(Type.IP_ADDRESS, "127.0.0.*"), new ClientBwListEntryDTO(Type.IP_ADDRESS, "192.168.0.1"), new ClientBwListEntryDTO(Type.IP_ADDRESS, "1...
@Override public boolean isRegistered(JobID jobId) { return jobManagerRunners.containsKey(jobId); }
@Test void testIsNotRegistered() { assertThat(testInstance.isRegistered(new JobID())).isFalse(); }
public List<PrometheusQueryResult> queryMetric(String queryString, long startTimeMs, long endTimeMs) throws IOException { URI queryUri = URI.create(_prometheusEndpoint.toURI() + QUERY_RANGE_API_PATH); H...
@Test(expected = IOException.class) public void testEmptyResult() throws Exception { this.serverBootstrap.registerHandler(PrometheusAdapter.QUERY_RANGE_API_PATH, new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) {...
static ContainerPopulator<TaskContainer> newContainerPopulator(CeTask task) { return taskContainer -> { taskContainer.add(task); taskContainer.add(AuditHousekeepingFrequencyHelper.class); taskContainer.add(AuditPurgeStep.class); taskContainer.add(new AuditPurgeComputationSteps(taskContainer)...
@Test public void newContainerPopulator() { CeTask task = new CeTask.Builder() .setUuid("TASK_UUID") .setType("Type") .build(); AuditPurgeTaskProcessor.newContainerPopulator(task).populateContainer(container); Mockito.verify(container, Mockito.times(5)).add(any()); }
public EnumSet<E> get() { return value; }
@SuppressWarnings("unchecked") @Test public void testSerializeAndDeserializeNonEmpty() throws IOException { DataOutputBuffer out = new DataOutputBuffer(); ObjectWritable.writeObject(out, nonEmptyFlagWritable, nonEmptyFlagWritable .getClass(), null); DataInputBuffer in = new DataInputBuffer(); ...
@Override public void serialize(Asn1OutputStream out, BigInteger obj) { final byte[] data = obj.toByteArray(); if (data[0] == 0) { out.write(data, 1, data.length - 1); } else { out.write(data); } }
@Test public void shouldSerialize() { assertArrayEquals( new byte[] { -128 }, serialize(new BigIntegerConverter(), BigInteger.class, BigInteger.valueOf(128)) ); }
public static Gson instance() { return SingletonHolder.INSTANCE; }
@Test void rejectsDeserializationOfAESEncrypter() { final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Serialization.instance().fromJson("{}", AESEncrypter.class)); assertEquals(format("Refusing to deserialize a %s in the JSON stream!", AESEncrypter...
@Override public boolean isGatheringMetrics() { return gatheringMetrics; }
@Test public void isGatheringMetricsTest() { JobMeta jobMetaTest = new JobMeta(); jobMetaTest.setGatheringMetrics( true ); assertTrue( jobMetaTest.isGatheringMetrics() ); jobMetaTest.setGatheringMetrics( false ); assertFalse( jobMetaTest.isGatheringMetrics() ); }