focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
String getProviderURL(LdapName baseDN) throws NamingException { StringBuffer ldapURL = new StringBuffer(); try { for ( String host : hosts ) { // Create a correctly-encoded ldap URL for the PROVIDER_URL final URI uri = new URI(sslEnabl...
@Test public void testGetProviderURLWithSpaces() throws Exception { // Setup fixture. final Map<String, String> properties = new HashMap<>(); properties.put("ldap.host", "localhost"); properties.put("ldap.port", "389"); properties.put("ldap.sslEnabled", "false"); ...
@Override public void convertWeightsForChildQueues(FSQueue queue, CapacitySchedulerConfiguration csConfig) { List<FSQueue> children = queue.getChildQueues(); if (queue instanceof FSParentQueue || !children.isEmpty()) { QueuePath queuePath = new QueuePath(queue.getName()); if (queue.getName(...
@Test public void testNoChildQueueConversion() { FSQueue root = createFSQueues(); converter.convertWeightsForChildQueues(root, csConfig); assertEquals("root weight", 1.0f, csConfig.getNonLabeledQueueWeight(ROOT), 0.0f); assertEquals("Converted items", 21, csConfig.getPropsWithPrefix(P...
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowTablePattern() throws AnalysisException, DdlException { ShowTableStmt stmt = new ShowTableStmt("testDb", false, "empty%"); ShowResultSet resultSet = ShowExecutor.execute(stmt, ctx); Assert.assertFalse(resultSet.next()); }
public Set<MessageQueueAssignment> queryAssignment(final String topic, final String consumerGroup, final String strategyName, final MessageModel messageModel, int timeout) throws RemotingException, InterruptedException, MQBrokerException { String brokerAddr = this.findBrokerAddrByTopic(topic); ...
@Test public void testQueryAssignment() throws MQBrokerException, RemotingException, InterruptedException { topicRouteTable.put(topic, createTopicRouteData()); brokerAddrTable.put(defaultBroker, createBrokerAddrMap()); consumerTable.put(group, createMQConsumerInner()); Set<MessageQue...
@GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); }
@Test public void getPostById() throws Exception { this.rest .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this....
protected boolean isNodeEmpty(JsonNode json) { if (json.isArray()) { return isListEmpty((ArrayNode) json); } else if (json.isObject()) { return isObjectEmpty((ObjectNode) json); } else { return isEmptyText(json); } }
@Test public void isNodeEmpty_objectNode() { ObjectNode objectNode = new ObjectNode(factory); assertThat(expressionEvaluator.isNodeEmpty(objectNode)).isTrue(); }
public static Write ingestMessages(String hl7v2Store) { return write(hl7v2Store).setWriteMethod(Write.WriteMethod.INGEST).build(); }
@Test public void testHL7v2IOFailedWrites() { Message msg = new Message().setData(""); List<HL7v2Message> emptyMessages = Collections.singletonList(HL7v2Message.fromModel(msg)); PCollection<HL7v2Message> messages = pipeline.apply(Create.of(emptyMessages).withCoder(new HL7v2MessageCoder())); ...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 2) { onInvalidDataReceived(device, data); return; } // Read the Op Code final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); // Estima...
@Test public void onContinuousGlucoseCalibrationValueReceived() { final MutableData data = new MutableData(new byte[11]); data.setValue(6, Data.FORMAT_UINT8, 0); data.setValue(1, 2, Data.FORMAT_SFLOAT, 1); data.setValue(10, Data.FORMAT_UINT16_LE, 3); data.setValue(0x32, Data.FORMAT_UINT8, 5); data.setValue...
@Override public ProcResult fetchResult() throws AnalysisException { Preconditions.checkNotNull(globalStateMgr); BaseProcResult result = new BaseProcResult(); result.setNames(TITLE_NAMES); List<String> dbNames = globalStateMgr.getLocalMetastore().listDbNames(); if (dbNames =...
@Test public void testFetchResultInvalid() throws AnalysisException { new Expectations(globalStateMgr) { { globalStateMgr.getLocalMetastore().listDbNames(); minTimes = 0; result = null; } }; DbsProcDir dir; Proc...
@SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/20497) }) public static Row structToBeamRow(Struct struct, Schema schema) { Map<String, @Nullable Object> structValues = schema.getFields().stream() .collect( HashMap::new, (map, ...
@Test public void testStructToBeamRowFailsColumnsDontMatch() { Schema schema = Schema.builder().addInt64Field("f_int64").build(); Struct struct = Struct.newBuilder().set("f_different_field").to(5L).build(); Exception exception = assertThrows( IllegalArgumentException.class, () -> Struc...
public int[] findMatchingLines(List<String> left, List<String> right) { int[] index = new int[right.size()]; int dbLine = left.size(); int reportLine = right.size(); try { PathNode node = new MyersDiff<String>().buildPath(left, right); while (node.prev != null) { PathNode prevNode ...
@Test public void shouldDetectWhenEndingWithModifiedLines() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add(...
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldValidateTerminateAllQuery() { // Given: givenTerminateAll(); // When: commandFactory.create(configuredStatement, executionContext); // Then: verify(query1).close(); verify(query2).close(); }
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testMissedInvertedMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("something", "30"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher...
ControllerResult<Map<String, ApiError>> updateFeatures( Map<String, Short> updates, Map<String, FeatureUpdate.UpgradeType> upgradeTypes, boolean validateOnly ) { TreeMap<String, ApiError> results = new TreeMap<>(); List<ApiMessageAndVersion> records = BoundedL...
@Test public void testUnsafeDowngradeIsTemporarilyDisabled() { FeatureControlManager manager = TEST_MANAGER_BUILDER1.build(); assertEquals(ControllerResult.of(Collections.emptyList(), singletonMap(MetadataVersion.FEATURE_NAME, new ApiError(Errors.INVALID_UPDATE_VERSION, ...
public static AuditManagerS3A stubAuditManager() { return new NoopAuditManagerS3A(); }
@Test public void testNoopAuditManager() throws Throwable { AuditManagerS3A manager = AuditIntegration.stubAuditManager(); assertThat(manager.createTransferListener()) .describedAs("transfer listener") .isNotNull(); }
public void acquireWriteLock(String key) { getLock(key).writeLock().lock(); }
@Test public void shouldEnforceMutualExclusionOfWriteLockForGivenName() throws InterruptedException { readWriteLock.acquireWriteLock("foo"); new Thread(() -> { readWriteLock.acquireWriteLock("foo"); numberOfLocks++; }).start(); Thread.sleep(1000); a...
public final T apply(Schema left, Schema right) { return visit(this, Context.EMPTY, FieldType.row(left), FieldType.row(right)); }
@Test public void testListCommonFields() { assertThat( new ListCommonFields().apply(LEFT, RIGHT), containsInAnyOrder("f0", "f1", "f2", "f3", "f3.f0", "f3.f1")); }
Object getCellValue(Cell cell, Schema.FieldType type) { ByteString cellValue = cell.getValue(); int valueSize = cellValue.size(); switch (type.getTypeName()) { case BOOLEAN: checkArgument(valueSize == 1, message("Boolean", 1)); return cellValue.toByteArray()[0] != 0; case BYTE: ...
@Test public void shouldParseByteType() { byte[] value = new byte[] {2}; assertEquals((byte) 2, PARSER.getCellValue(cell(value), BYTE)); }
@Override public void cleanHistoryConfig() { Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * getRetentionDays()); int pageSize = 1000; LOGGER.warn("clearConfigHistory, getBeforeStamp:{}, pageSize:{}", startTime, pageSize); getHistoryConfigInfoPersistService().re...
@Test public void testCleanHistoryConfig() throws Exception { defaultHistoryConfigCleaner.cleanHistoryConfig(); Mockito.verify(historyConfigInfoPersistService, Mockito.times(1)) .removeConfigHistory(any(Timestamp.class), anyInt()); }
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testExpire() throws InterruptedException { RMapCacheNative<String, String> cache = redisson.getMapCacheNative("simple"); cache.put("0", "8", Duration.ofSeconds(1)); cache.expire(Duration.ofMillis(100)); Thread.sleep(500); Assertions.assertEquals(0, cache....
public static Comparator<StructLike> forType(Types.StructType struct) { return new StructLikeComparator(struct); }
@Test public void testUuid() { assertComparesCorrectly( Comparators.forType(Types.UUIDType.get()), UUID.fromString("81873e7d-1374-4493-8e1d-9095eff7046c"), UUID.fromString("fd02441d-1423-4a3f-8785-c7dd5647e26b")); }
public static Date getDate(Object date) { return getDate(date, Calendar.getInstance().getTime()); }
@Test @SuppressWarnings({ "UndefinedEquals", "JavaUtilDate" }) public void testGetDateObjectDateWithTimeAndNullDefault() { Date time = new Date(); assertEquals(time, Converter.getDate(time, null)); }
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Meter meter = registry.meter(metricsName); Long mark = endpoint.getMark(); Long finalMark = getLo...
@Test public void testProcessMarkSetOverrideByHeaderValue() throws Exception { when(endpoint.getMark()).thenReturn(MARK); when(in.getHeader(HEADER_METER_MARK, MARK, Long.class)).thenReturn(MARK + 101); producer.doProcess(exchange, endpoint, registry, METRICS_NAME); inOrder.verify(exc...
static JavaType constructType(Type type) { try { return constructTypeInner(type); } catch (Exception e) { throw new InvalidDataTableTypeException(type, e); } }
@Test <T> void type_variables_are_not_allowed() { Type typeVariable = new TypeReference<List<List<T>>>() { }.getType(); InvalidDataTableTypeException exception = assertThrows( InvalidDataTableTypeException.class, () -> TypeFactory.constructType(typeVariable)); ...
@Override public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { if(proxy.isSupported(source, target)) { return proxy.copy(source, target, status, callback, listener); ...
@Test public void testCopyFileWithRenameBetweenEncryptedDataRooms() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room1 = new SDSDirectoryFeature(session, nodeid).createRoom( new Path(new AlphanumericRandomStringService().random(), Enu...
public static Object parse(String element) throws PathSegment.PathSegmentSyntaxException { Queue<Token> tokens = tokenizeElement(element); Object result = parseElement(tokens); if (!tokens.isEmpty()) { throw new PathSegment.PathSegmentSyntaxException("tokens left over after parsing; first exces...
@Test(dataProvider = "unicode") public void testUnicode(String decodable, Object expectedObj) throws PathSegment.PathSegmentSyntaxException { Object actualObj = URIElementParser.parse(decodable); Assert.assertEquals(actualObj, expectedObj); }
public ProtocolBuilder server(String server) { this.server = server; return getThis(); }
@Test void server() { ProtocolBuilder builder = new ProtocolBuilder(); builder.server("server"); Assertions.assertEquals("server", builder.build().getServer()); }
@NotNull @Override public Optional<? extends Algorithm> parse( @Nullable String str, @NotNull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } return switch (str) { case "DHE", "DH" -> Optional.of(new DH(KeyAgreement.cl...
@Test public void test() { final DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); final KeyExchangeAlgorithmMapper mapper = new KeyExchangeAlgorithmMapper(); final Collection<String> kexCollection = ...
public static synchronized HostPasswordStore get() { try { return new PasswordStoreFactory().create(); } catch(FactoryException e) { return new DisabledPasswordStore(); } }
@Test public void testGet() { assertNotSame(PasswordStoreFactory.get(), PasswordStoreFactory.get()); }
@PostMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE, signType = SignType.CONSOLE) public Result<Boolean> createNamespace(NamespaceForm namespaceForm) throws NacosException { namespaceForm.validate(); ...
@Test void testEditNamespaceWithIllegalName() { NamespaceForm form = new NamespaceForm(); form.setNamespaceId("test-id"); form.setNamespaceDesc("testDesc"); form.setNamespaceName("test@Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNames...
@Override public ValidationResult responseMessageForIsPackageConfigurationValid(String responseBody) { return jsonResultMessageHandler.toValidationResult(responseBody); }
@Test public void shouldBuildValidationResultForCheckRepositoryConfigurationValidResponse() throws Exception { String responseBody = "[{\"key\":\"key-one\",\"message\":\"incorrect value\"},{\"message\":\"general error\"}]"; ValidationResult validationResult = messageHandler.responseMessageForIsPacka...
public static VirtualSlotRef read(DataInput in) throws IOException { VirtualSlotRef virtualSlotRef = new VirtualSlotRef(null, Type.BIGINT, null, new ArrayList<>()); virtualSlotRef.readFields(in); return virtualSlotRef; }
@Test public void read() throws IOException { virtualSlot.write(dos); virtualSlot.setRealSlots(slots); VirtualSlotRef v = VirtualSlotRef.read(dis); Assert.assertEquals(3, v.getRealSlots().size()); }
@Override public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return outerJoin(otherStream, toValueJoin...
@Test public void shouldNotAllowNullJoinWindowsOnOuterJoinWithStreamJoined() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.outerJoin( testStream, MockValueJoiner.TOSTRING_JOINER, nul...
@Override public void error(String code, String cause, String extendedInformation, String msg) { if (getDisabled()) { return; } try { getLogger().error(appendContextMessageWithInstructions(code, cause, extendedInformation, msg)); } catch (Throwable t) { ...
@Test void testGetLogger() { Assertions.assertThrows(RuntimeException.class, () -> { Logger failLogger = mock(Logger.class); FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger); doThrow(new RuntimeException()).when(failLogger).error...
@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 testCallOnce() { run( "def uuid = function(){ return java.util.UUID.randomUUID() + '' }", "def first = callonce uuid", "def second = callonce uuid" ); matchVar("first", get("second")); }
@Override public V get(K name) { return null; }
@Test public void testGet() { assertNull(HEADERS.get("name1")); }
public static void main(String[] args) throws Exception { main(System::getenv); }
@Test @SuppressWarnings("FutureReturnValueIgnored") // failure will cause test to timeout. public void testLaunchFnHarnessAndTeardownCleanly() throws Exception { Function<String, String> environmentVariableMock = mock(Function.class); PipelineOptions options = PipelineOptionsFactory.create(); when(env...
public Map<String, String> getHeaders() { return _headers; }
@Test public void testHeadersCaseInsensitiveAdd() { final long id = 42l; GetRequestBuilder<Long, TestRecord> builder = generateDummyRequestBuilder(); Request<TestRecord> request = builder .id(id) .addHeader("header", "value1") .addHeader("HEADER", "value2") .build(); ...
@Override public void run() { ContainerId containerId = container.getContainerId(); String containerIdStr = containerId.toString(); LOG.info("Cleaning up container " + containerIdStr); try { context.getNMStateStore().storeContainerKilled(containerId); } catch (IOException e) { LOG.err...
@Test public void testNoCleanupWhenContainerNotLaunched() throws IOException { cleanup.run(); verify(launch, Mockito.times(0)).signalContainer( Mockito.any(SignalContainerCommand.class)); }
@Override public final long readLong() throws EOFException { final long l = readLong(pos); pos += LONG_SIZE_IN_BYTES; return l; }
@Test public void testReadLongByteOrder() throws Exception { long readLong = in.readLong(LITTLE_ENDIAN); long longB = Bits.readLongL(INIT_DATA, 0); assertEquals(longB, readLong); }
public static String sanitizeUri(String uri) { // use xxxxx as replacement as that works well with JMX also String sanitized = uri; if (uri != null) { sanitized = ALL_SECRETS.matcher(sanitized).replaceAll("$1=xxxxxx"); sanitized = USERINFO_PASSWORD.matcher(sanitized).repl...
@Test public void testSanitizeUriWithUserInfoAndColonPassword() { String uri = "sftp://USERNAME:HARRISON:COLON@sftp.server.test"; String expected = "sftp://USERNAME:xxxxxx@sftp.server.test"; assertEquals(expected, URISupport.sanitizeUri(uri)); }
public static Builder newTimestampColumnDefBuilder() { return new Builder(); }
@Test public void build_column_def_with_only_required_attributes() { TimestampColumnDef def = newTimestampColumnDefBuilder() .setColumnName("created_at") .build(); assertThat(def.getName()).isEqualTo("created_at"); assertThat(def.isNullable()).isTrue(); assertThat(def.getDefaultValue()).i...
public static String normalize(String path) { if (path == null) { return null; } //兼容Windows下的共享目录路径(原始路径如果以\\开头,则保留这种路径) if (path.startsWith("\\\\")) { return path; } // 兼容Spring风格的ClassPath路径,去除前缀,不区分大小写 String pathToUse = StrUtil.removePrefixIgnoreCase(path, URLUtil.CLASSPATH_URL_PREFIX); // ...
@Test public void normalizeBlankTest() { assertEquals("C:/aaa ", FileUtil.normalize("C:\\aaa ")); }
@Override public int hashCode() { return Objects.hash(from, to); }
@Test public void testHashCode() { assertThat(new LineRange(12, 15)).hasSameHashCodeAs(new LineRange(12, 15)); }
@Override public void encode(DataSchema schema) throws IOException { // Initialize a new builder for the preferred encoding style _builder = _encodingStyle.newBuilderInstance(_writer); // Set and write root namespace/package if (schema instanceof NamedDataSchema) { NamedDataSchema namedSc...
@Test public void testEncodeRecordWithEmptyDataMapInProperty() throws IOException { RecordDataSchema source = new RecordDataSchema(new Name("com.linkedin.test.RecordDataSchema"), RecordDataSchema.RecordType.RECORD); Map<String, Object> properties = new HashMap<>(); properties.put("empty", new Da...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertByte() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.BYTE_TYPE).build(); BasicTypeDefine typeDefine = XuguTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions...
public ProviderConfig build() { ProviderConfig provider = new ProviderConfig(); super.build(provider); provider.setHost(host); provider.setPort(port); provider.setContextpath(contextpath); provider.setThreadpool(threadpool); provider.setThreadname(threadname); ...
@Test void build() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.host("host") .port(8080) .contextPath("contextpath") .threadPool("mockthreadpool") .threads(2) .ioThreads(3) .queues(4)...
public void add(String property, JsonElement value) { members.put(property, value == null ? JsonNull.INSTANCE : value); }
@Test public void testPropertyWithQuotes() { JsonObject jsonObj = new JsonObject(); jsonObj.add("a\"b", new JsonPrimitive("c\"d")); String json = new Gson().toJson(jsonObj); assertThat(json).isEqualTo("{\"a\\\"b\":\"c\\\"d\"}"); }
public ProtocolBuilder transporter(String transporter) { this.transporter = transporter; return getThis(); }
@Test void transporter() { ProtocolBuilder builder = new ProtocolBuilder(); builder.transporter("mocktransporter"); Assertions.assertEquals("mocktransporter", builder.build().getTransporter()); }
@Override public void exportData(JsonWriter writer) throws IOException { // version tag at the root writer.name(THIS_VERSION); writer.beginObject(); // clients list writer.name(CLIENTS); writer.beginArray(); writeClients(writer); writer.endArray(); writer.name(GRANTS); writer.beginArray(); wr...
@Test public void testExportRefreshTokens() throws IOException, ParseException { String expiration1 = "2014-09-10T22:49:44.090+00:00"; Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); when(mockedClient1.getClientId()).the...
@Override public CreateTopicsResult createTopics(final Collection<NewTopic> newTopics, final CreateTopicsOptions options) { final Map<String, KafkaFutureImpl<TopicMetadataAndConfig>> topicFutures = new HashMap<>(newTopics.size()); final CreatableTopicCollec...
@Test public void testCreateTopics() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse( expectCreateTopicsRequestWithTopics("myTopic"), ...
public OffsetFetchResponseData.OffsetFetchResponseGroup fetchAllOffsets( OffsetFetchRequestData.OffsetFetchRequestGroup request, long lastCommittedOffset ) throws ApiException { final boolean requireStable = lastCommittedOffset == Long.MAX_VALUE; try { validateOffsetFetc...
@Test public void testFetchAllOffsetsWithUnknownGroup() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); assertEquals(Collections.emptyList(), context.fetchAllOffsets("group", Long.MAX_VALUE)); }
public FEELFnResult<Object> invoke(@ParameterName("list") List list) { if ( list == null || list.isEmpty() ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty")); } else { try { return FEELFnResult.ofResult(C...
@Test void invokeArrayOfChronoPeriods() { final ChronoPeriod p1Period = Period.parse("P1Y"); final ChronoPeriod p1Comparable = ComparablePeriod.parse("P1Y"); final ChronoPeriod p2Period = Period.parse("P1M"); final ChronoPeriod p2Comparable = ComparablePeriod.parse("P1M"); Pr...
public long scan( final UnsafeBuffer termBuffer, final long rebuildPosition, final long hwmPosition, final long nowNs, final int termLengthMask, final int positionBitsToShift, final int initialTermId) { boolean lossFound = false; int rebuildOff...
@Test void shouldNakMissingData() { final long rebuildPosition = ACTIVE_TERM_POSITION; final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L); insertDataFrame(offsetOfMessage(0)); insertDataFrame(offsetOfMessage(2)); lossDetector.scan(termBuffer, re...
public KVConfigManager getKvConfigManager() { return kvConfigManager; }
@Test public void getKvConfigManager() { KVConfigManager manager = namesrvController.getKvConfigManager(); Assert.assertNotNull(manager); }
@Override public ExecuteContext before(ExecuteContext context) { if (shouldHandle(context)) { ThreadLocalUtils.removeRequestTag(); ServerWebExchange exchange = (ServerWebExchange) context.getArguments()[0]; ServerHttpRequest request = exchange.getRequest(); Ht...
@Test public void testBefore() { // Test the before method interceptor.before(context); RequestTag requestTag = ThreadLocalUtils.getRequestTag(); Map<String, List<String>> header = requestTag.getTag(); Assert.assertNotNull(header); Assert.assertEquals(2, header.size()...
public String serializeToString() { switch (bitmapType) { case EMPTY: break; case SINGLE_VALUE: return String.format("%s", singleValue); case BITMAP_VALUE: return this.bitmap.serializeToString(); case SET_VALUE: ...
@Test public void testSerializeToString() { Assert.assertEquals(emptyBitmap.serializeToString(), ""); Assert.assertEquals(singleBitmap.serializeToString(), "1"); Assert.assertEquals(mediumBitmap.serializeToString(), "0,1,2,3,4,5,6,7,8,9"); Assert.assertEquals(largeBitmap.serializeToS...
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createVirtualNetwork(InputStream stream) { try { final TenantId tid = TenantId.tenantId(getFromJsonStream(stream, "id").asText()); VirtualNetwork newVnet = vnetAdminService.creat...
@Test public void testPostVirtualNetwork() { expect(mockVnetAdminService.createVirtualNetwork(tenantId2)).andReturn(vnet1); expectLastCall(); replay(mockVnetAdminService); WebTarget wt = target(); InputStream jsonStream = TenantWebResourceTest.class .getReso...
@Override public int run(String[] args) throws Exception { if (args.length != 2) { return usage(args); } String action = args[0]; String name = args[1]; int result; if (A_LOAD.equals(action)) { result = loadClass(name); } else if (A_CREATE.equals(action)) { //first load t...
@Test public void testCreateFailsPrivateClass() throws Throwable { run(FindClass.E_CREATE_FAILED, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass$PrivateClass"); }
public static void readJobRep( Object object, Repository rep, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException { try { String jobXML = rep.getJobEntryAttributeString( id_step, "job-xml" ); ByteArrayInputStream bais = new ByteArrayInputStream( jobXML.getBytes() ); Document do...
@Test( expected = NullPointerException.class ) public void readingJobRepoThrowsExceptionWhenParsingXmlWithBigAmountOfExternalEntities() throws Exception { SerializationHelper.readJobRep( null, repo, null, new ArrayList<>() ); }
public InetAddress resolve(final String name, final String uriParamName, final boolean isReResolution) { InetAddress resolvedAddress = null; try { resolvedAddress = InetAddress.getByName(name); } catch (final UnknownHostException ignore) { } ...
@Test void resolveReturnsNullForUnknownHost() { final String hostName = UUID.randomUUID().toString(); final String uriParamName = "endpoint"; final boolean isReResolution = false; assertNull(nameResolver.resolve(hostName, uriParamName, isReResolution)); }
@Override public void init() throws LoadException { createEtlJobConf(); }
@Test public void testRangePartitionHashDistribution(@Injectable SparkLoadJob sparkLoadJob, @Injectable SparkResource resource, @Injectable BrokerDesc brokerDesc, ...
@Override public void judgeContinueToExecute(final SQLStatement statement) throws SQLException { ShardingSpherePreconditions.checkState(statement instanceof CommitStatement || statement instanceof RollbackStatement, () -> new SQLFeatureNotSupportedException("Current transaction is aborted, c...
@Test void assertJudgeContinueToExecuteWithCommitStatement() { assertDoesNotThrow(() -> allowedSQLStatementHandler.judgeContinueToExecute(mock(CommitStatement.class))); }
@Override public void registerInstance(String namespaceId, String serviceName, Instance instance) throws NacosException { NamingUtils.checkInstanceIsLegal(instance); boolean ephemeral = instance.isEphemeral(); String clientId = IpPortBasedClient.getClientId(instance.toInetAddr(), ep...
@Test void testRegisterInstanceWithInvalidClusterName() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { Instance instance = new Instance(); instance.setEphemeral(true); instance.setClusterName("cluster1,cluster2"); ...
@Override public List<?> deserialize(final String topic, final byte[] bytes) { if (bytes == null) { return null; } try { final String recordCsvString = new String(bytes, StandardCharsets.UTF_8); final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat) .ge...
@Test public void shouldDeserializeDelimitedCorrectly() { // Given: final byte[] bytes = "1511897796092,1,item_1,10.0,10.10,100,10,100,ew==\r\n".getBytes(StandardCharsets.UTF_8); // When: final List<?> result = deserializer.deserialize("", bytes); // Then: assertThat(result, contains(1511897...
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for eac...
@Test(expected=AclException.class) public void testReplaceAclEntriesResultTooLarge() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); ...
int asyncBackups(int requestedSyncBackups, int requestedAsyncBackups, boolean syncForced) { if (syncForced || requestedAsyncBackups == 0) { // if syncForced, then there will never be any async backups (they are forced to become sync) // if there are no asyncBackups then we are also done....
@Test public void asyncBackups_whenForceSyncEnabled() { setup(true); // when forceSync is enabled, then async should always be 0 assertEquals(0, backupHandler.asyncBackups(0, 0, FORCE_SYNC_ENABLED)); assertEquals(0, backupHandler.asyncBackups(0, 1, FORCE_SYNC_ENABLED)); asse...
Future<Boolean> canRollController(int nodeId) { LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId); return describeMetadataQuorum().map(info -> { boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info); if (!canRoll) { ...
@Test public void canRollActiveControllerEvenSizedCluster(VertxTestContext context) { Map<Integer, OptionalLong> controllers = new HashMap<>(); controllers.put(1, OptionalLong.of(10000L)); controllers.put(2, OptionalLong.of(9500L)); controllers.put(3, OptionalLong.of(9700L)); ...
public static String builderData(final String paramType, final String paramName, final ServerWebExchange exchange) { return newInstance(paramType).builder(paramName, exchange); }
@Test public void testBuildHostData() { ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); SpringBeanUtils.getInstance().setApplicationContext(context); RemoteAddressResolver remoteAddressResolver = new RemoteAddressResolver() { }; ServerWebE...
public static String keyToString(Object key, URLEscaper.Escaping escaping, UriComponent.Type componentType, boolean full, ProtocolVersion version) { if (version.compareTo(All...
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "complexKey") public void testComplexKeyToString(ProtocolVersion version, String full, String notFull) { MyComplexKey myComplexKey1 = new MyComplexKey(); myComplexKey1.setA("stringVal"); myComplexKey1.setB(3); MyComplexKey myComplexKey2...
@Override public WatchKey register(final Watchable folder, final WatchEvent.Kind<?>[] events, final WatchEvent.Modifier... modifiers) throws IOException { if(null == monitor) { monitor = FileSystems.getDefault().newWatchService(); } final WatchKey key...
@Test(expected = IOException.class) public void testNotfound() throws Exception { final FileWatcher watcher = new FileWatcher(new NIOEventWatchService()); final Local file = new Local(System.getProperty("java.io.tmpdir") + "/notfound", UUID.randomUUID().toString()); assertFalse(file.exists()...
@Override @Nullable public double[] readDoubleArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, DOUBLE_ARRAY, super::readDoubleArray); }
@Test public void testReadDoubleArray() throws Exception { assertNull(reader.readDoubleArray("NO SUCH FIELD")); }
@Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { try { String partitionColumn = job.get(Constants.JDBC_PARTITION_COLUMN); int numPartitions = job.getInt(Constants.JDBC_NUM_PARTITIONS, -1); String lowerBound = job.get(Constants.JDBC_LOW_BOUND); Strin...
@Test public void testIntervalSplit_Timestamp() throws HiveJdbcDatabaseAccessException, IOException { JdbcInputFormat f = new JdbcInputFormat(); when(mockDatabaseAccessor.getColumnNames(any(Configuration.class))).thenReturn(Lists.newArrayList("a")); when(mockDatabaseAccessor.getBounds(any(Configuration.cl...
protected Authorization parseAuthLine(String line) throws ParseException { String[] tokens = line.split("\\s+"); String keyword = tokens[0].toLowerCase(); switch (keyword) { case "topic": return createAuthorization(line, tokens); case "user": ...
@Test public void testParseAuthLineValid_read() throws ParseException { Authorization authorization = authorizator.parseAuthLine("topic read /weather/italy/anemometer"); // Verify assertEquals(R_ANEMOMETER, authorization); }
@Override public Set<GPUInfo> retrieveResourceInfo(long gpuAmount) throws Exception { Preconditions.checkArgument( gpuAmount > 0, "The gpuAmount should be positive when retrieving the GPU resource information."); final Set<GPUInfo> gpuResources = new HashSet<>(); ...
@Test void testGPUDriverWithTestScript() throws Exception { final int gpuAmount = 2; final Configuration config = new Configuration(); config.set(GPUDriverOptions.DISCOVERY_SCRIPT_PATH, TESTING_DISCOVERY_SCRIPT_PATH); final GPUDriver gpuDriver = new GPUDriver(config); final ...
public static <T> Deserializer<T> deserializer(final Class<T> clazz) { return new InternalTopicDeserializer<>(clazz); }
@Test public void shouldUsePlanMapperForDeserialize() { // When: final Expression deserialized = InternalTopicSerdes.deserializer(Expression.class).deserialize( "", "\"(123 + 456)\"".getBytes(Charset.defaultCharset()) ); // Then: assertThat(deserialized, equalTo(EXPRESSION)); }
@Override public List<String> getTenantIdList(int page, int pageSize) { PaginationHelper<Map<String, Object>> helper = createPaginationHelper(); ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); ...
@Test void testGetTenantIdList() { //mock select config state List<String> tenantStrings = Arrays.asList("tenant1", "tenant2", "tenant3"); Map<String, Object> g1 = new HashMap<>(); g1.put("TENANT_ID", tenantStrings.get(0)); Map<String, Object> g2 = new HashMap<>(); ...
@Override public Map<Errors, Integer> errorCounts() { if (data.errorCode() != Errors.NONE.code()) // Minor optimization since the top-level error applies to all partitions return Collections.singletonMap(error(), data.partitionErrors().size() + 1); Map<Errors, Integer> errors...
@Test public void testErrorCountsWithTopLevelError() { List<StopReplicaPartitionError> errors = new ArrayList<>(); errors.add(new StopReplicaPartitionError().setTopicName("foo").setPartitionIndex(0)); errors.add(new StopReplicaPartitionError().setTopicName("foo").setPartitionIndex(1) ...
@Override public File selectAllocationBaseDirectory(int idx) { return allocationBaseDirs[idx]; }
@Test void selectAllocationBaseDir() { for (int i = 0; i < allocBaseFolders.length; ++i) { assertThat(directoryProvider.selectAllocationBaseDirectory(i)) .isEqualTo(allocBaseFolders[i]); } }
public static boolean isEmpty(String str) { return str == null || str.length() == 0; }
@Test public void testIsEmpty() { Assert.assertFalse(StringUtil.isEmpty("bar")); Assert.assertTrue(StringUtil.isEmpty("")); }
boolean needsMigration() { File mappingFile = UserIdMapper.getConfigFile(usersDirectory); if (mappingFile.exists() && mappingFile.isFile()) { LOGGER.finest("User mapping file already exists. No migration needed."); return false; } File[] userDirectories = listUser...
@Test public void needsMigrationNoneExisting() throws IOException { UserIdMigrator migrator = createUserIdMigrator(); assertThat(migrator.needsMigration(), is(false)); }
public static String processingLogTopic( final ProcessingLogConfig config, final KsqlConfig ksqlConfig ) { final String topicNameConfig = config.getString(ProcessingLogConfig.TOPIC_NAME); if (topicNameConfig.equals(ProcessingLogConfig.TOPIC_NAME_NOT_SET)) { return String.format( "%...
@Test public void shouldReturnProcessingLogTopic() { // Given/When final ProcessingLogConfig processingLogConfig = new ProcessingLogConfig(ImmutableMap.of()); final String processingLogTopic = ReservedInternalTopics.processingLogTopic( processingLogConfig, ksqlConfig); // Then assertThat(...
@Override public Flux<RawMetric> retrieve(KafkaCluster c, Node node) { log.debug("Retrieving metrics from prometheus exporter: {}:{}", node.host(), c.getMetricsConfig().getPort()); MetricsConfig metricsConfig = c.getMetricsConfig(); var webClient = new WebClientConfigurator() .configureBufferSize...
@Test void callsSecureMetricsEndpointAndConvertsResponceToRawMetric() { var url = mockWebServer.url("/metrics"); mockWebServer.enqueue(prepareResponse()); MetricsConfig metricsConfig = prepareMetricsConfig(url.port(), "username", "password"); StepVerifier.create(retriever.retrieve(WebClient.create(...
public static long makeTemplate(TemplateMakerConfig templateMakerConfig) { Meta meta = templateMakerConfig.getMeta(); String originProjectPath = templateMakerConfig.getOriginProjectPath(); TemplateMakerFileConfig templateMakerFileConfig = templateMakerConfig.getFileConfig(); TemplateMake...
@Test public void makeTemplateBug2() { System.out.println("------------------- 测试Spring boot init 项目 makeTemplateBug2 ------------------"); Meta meta = new Meta(); // 基本信息 meta.setName("spring boot init "); meta.setDescription("spring boot 初始化项目"); String proje...
@Override public ObjectNode encode(Host host, CodecContext context) { checkNotNull(host, NULL_OBJECT_MSG); final JsonCodec<HostLocation> locationCodec = context.codec(HostLocation.class); // keep fields in string for compatibility final ObjectNode result = context.ma...
@Test public void testEncode() throws IOException { InputStream jsonStream = HostCodec.class.getResourceAsStream(JSON_FILE); JsonNode jsonString = context.mapper().readTree(jsonStream); ObjectNode expected = hostCodec.encode(HOST, context); // Host ID is not a field in Host but rath...
@Override @Nullable public char[] readCharArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { char[] values = new char[len]; for (int i = 0; i < len; i++) { values[i] ...
@Test public void testReadCharArray() throws Exception { byte[] bytesBE = {0, 0, 0, 0, 0, 0, 0, 1, 0, 1, -1, -1, -1, -1}; byte[] bytesLE = {0, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, -1, -1, -1}; in.init((byteOrder == BIG_ENDIAN ? bytesBE : bytesLE), 0); in.position(10); char[] theNu...
public void listenToService(String serviceName) { _watchedServiceResources.computeIfAbsent(serviceName, k -> { XdsClient.NodeResourceWatcher watcher = getServiceResourceWatcher(serviceName); _xdsClient.watchXdsResource(D2_SERVICE_NODE_PREFIX + serviceName, watcher); return watcher; }); ...
@Test(dataProvider = "provideTransportClientProperties") public void testListenToService(Map<String, Object> clientOverride, Map<String, Object> original, Map<String, Object> overridden) { XdsToD2PropertiesAdaptorFixture fixture = new XdsToD2PropertiesAdaptorFixture(); String serviceName = "FooService...
public static int readUint16(ByteBuffer buf) throws BufferUnderflowException { return Short.toUnsignedInt(buf.order(ByteOrder.LITTLE_ENDIAN).getShort()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testReadUint16ThrowsException1() { ByteUtils.readUint16(new byte[]{1}, 2); }
protected synchronized void addSoftwareIdentifiers(Set<Identifier> identifiers) { this.softwareIdentifiers.addAll(identifiers); }
@Test public void testAddSoftwareIdentifiers() { Set<Identifier> identifiers = new HashSet<>(); Dependency instance = new Dependency(); instance.addSoftwareIdentifiers(identifiers); assertNotNull(instance.getSoftwareIdentifiers()); }
public static SchemaKStream<?> buildSource( final PlanBuildContext buildContext, final DataSource dataSource, final QueryContext.Stacker contextStacker ) { final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed(); switch (dataSource.getDataSourceType()) { case KST...
@Test public void shouldBuildWindowedStream() { // Given: givenWindowedStream(); // When: final SchemaKStream<?> result = SchemaKSourceFactory.buildSource( buildContext, dataSource, contextStacker ); // Then: assertThat(result, not(instanceOf(SchemaKTable.class)))...
public Map<String, Object> valuesWithPrefixAllOrNothing(String prefix) { Map<String, Object> withPrefix = originalsWithPrefix(prefix, true); if (withPrefix.isEmpty()) { return new RecordingMap<>(values(), "", true); } else { Map<String, Object> result = new RecordingMap<...
@Test public void testValuesWithPrefixAllOrNothing() { String prefix1 = "prefix1."; String prefix2 = "prefix2."; Properties props = new Properties(); props.put("sasl.mechanism", "PLAIN"); props.put("prefix1.sasl.mechanism", "GSSAPI"); props.put("prefix1.sasl.kerberos....
@Override public void execute(final ConnectionSession connectionSession) throws SQLException { MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts(); JDBCExecutor jdbcExecutor = new JDBCExecutor(BackendExecutorContext.getInstance().getExecutorEngine...
@Test void assertExecuteSelectVersion() throws SQLException { when(ProxyContext.getInstance()).thenReturn(mock(ProxyContext.class, RETURNS_DEEP_STUBS)); RuleMetaData ruleMetaData = mock(RuleMetaData.class); when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData...
private HostId(MacAddress mac, VlanId vlanId) { this.mac = mac; this.vlanId = vlanId; }
@Test public void basics() { new EqualsTester() .addEqualityGroup(hostId(MAC1, VLAN1), hostId(MAC1, VLAN1)) .addEqualityGroup(hostId(MAC2, VLAN2), hostId(MAC2, VLAN2)) .testEquals(); }
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(userF...
@Test @Parameters({ "true, __key", "false, this" }) public void when_fieldIsObjectAndClassDefinitionDoesNotExist_then_throws(boolean key, String prefix) { InternalSerializationService ss = new DefaultSerializationServiceBuilder().build(); Map<String, String> options =...
@Override public Column convert(BasicTypeDefine typeDefine) { Long typeDefineLength = typeDefine.getLength(); PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.get...
@Test public void testConvertBigint() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("bigint") .dataType("bigint") .build(); Column column = Iri...
@Override public String toString() { return reference; }
@Test public void testUnique() { final Path t_noregion = new Path("/", EnumSet.of(Path.Type.directory)); assertEquals("[directory]-/", new DefaultPathPredicate(t_noregion).toString()); final Path t_region = new Path("/", EnumSet.of(Path.Type.directory)); t_region.attributes().setRegi...
@Override public ExecuteContext after(ExecuteContext context) { ThreadLocalUtils.removeRequestData(); ThreadLocalUtils.removeRequestTag(); return context; }
@Test public void testAfter() { ThreadLocalUtils.setRequestTag(new RequestTag(null)); ThreadLocalUtils.setRequestData(new RequestData(null, null, null)); interceptor.after(context); Assert.assertNull(ThreadLocalUtils.getRequestTag()); Assert.assertNull(ThreadLocalUtils.getRe...
@Override public PageResult<NotifyMessageDO> getMyMyNotifyMessagePage(NotifyMessageMyPageReqVO pageReqVO, Long userId, Integer userType) { return notifyMessageMapper.selectPage(pageReqVO, userId, userType); }
@Test public void testGetMyNotifyMessagePage() { // mock 数据 NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> { // 等会查询到 o.setUserId(1L); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setReadStatus(true); o.setCreateTime(buildT...
@Override public boolean isNoop() { return true; }
@Test void isNoop() { assertThat(span.isNoop()).isTrue(); }
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) { return drlxParse(patternType, bindingId, expression, false); }
@Test public void testNullSafeExpressionsWithNotIn() { SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "address!.city not in (\"Milan\", \"Tokyo\")"); List<Expression> nullSafeExpressions = result.getNullSafeExpressions(); assertThat(nullSafeExp...