focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", namespaceId, serviceName, instance); String groupedServiceName = NamingUtils.get...
@Test void testRegisterService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult<Object> a = new HttpRestResult<Object>(); a.setData("127.0.0.1:8848"); a.setCode(200); when(nacosRestTemplate.exchangeForm(a...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsExactly_primitiveFloatArray_failure() { expectFailureWhenTestingThat(array(1.1f, 2.2f, 3.3f)) .usingExactEquality() .containsExactly(array(2.2f, 1.1f)); assertFailureKeys( "value of", "unexpected (1)", "---", "expected", "testing whether", "...
public ClassTemplateSpec generate(DataSchema schema, DataSchemaLocation location) { pushCurrentLocation(location); final ClassTemplateSpec result = processSchema(schema, null, null); popCurrentLocation(); return result; }
@Test(dataProvider = "customTypeDataForUnion") public void testCustomInfoForUnionMembers(final List<DataSchema> customTypedSchemas) { final UnionDataSchema union = new UnionDataSchema(); List<UnionDataSchema.Member> members = customTypedSchemas.stream() .map(UnionDataSchema.Member::new) .col...
private static Timestamp fromLong(Long elapsedSinceEpoch, TimestampPrecise precise) throws IllegalArgumentException { final long seconds; final int nanos; switch (precise) { case Millis: seconds = Math.floorDiv(elapsedSinceEpoch, (long) THOUSAND); nanos = (int) Math.floorMod(elapsedSinceEpo...
@Test void timestampMicrosConversionSecondsUpperLimit() throws Exception { assertThrows(IllegalArgumentException.class, () -> { TimestampMicrosConversion conversion = new TimestampMicrosConversion(); long exceeded = (ProtoConversions.SECONDS_UPPERLIMIT + 1) * 1000000; conversion.fromLong(exceede...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<>(); if(replies.isEmpty()) { return children; } // At least one entry successfully parsed...
@Test public void testParseMlsdMode664() throws Exception { Path path = new Path( "/www", EnumSet.of(Path.Type.directory)); String[] replies = new String[]{ "modify=19990307234236;perm=adfr;size=60;type=file;unique=FE03U10001724;UNIX.group=1001;UNIX.mode=0664;UNIX.own...
public RawLog newPublication(final long correlationId, final int termBufferLength, final boolean useSparseFiles) { return newInstance(publicationsDir, correlationId, termBufferLength, useSparseFiles); }
@Test void shouldCreateCorrectLengthAndZeroedFilesForPublication() { rawLog = fileStoreLogFactory.newPublication(CREATION_ID, TERM_BUFFER_LENGTH, PRE_ZERO_LOG); assertEquals(TERM_BUFFER_LENGTH, rawLog.termLength()); final UnsafeBuffer[] termBuffers = rawLog.termBuffers(); asser...
static int validatePubsubMessageSize(PubsubMessage message, int maxPublishBatchSize) throws SizeLimitExceededException { int payloadSize = message.getPayload().length; if (payloadSize > PUBSUB_MESSAGE_DATA_MAX_BYTES) { throw new SizeLimitExceededException( "Pubsub message data field of len...
@Test public void testValidatePubsubMessageSizeAttributeKeyTooLarge() { byte[] data = new byte[1024]; String attributeKey = RandomStringUtils.randomAscii(257); String attributeValue = "value"; Map<String, String> attributes = ImmutableMap.of(attributeKey, attributeValue); PubsubMessage message = n...
@Override public SchemaKGroupedTable groupBy( final FormatInfo valueFormat, final List<Expression> groupByExpressions, final Stacker contextStacker ) { // Since tables must have a key, we know that the keyFormat is both // not NONE and has at least one column; this allows us to inherit ...
@Test public void testGroupBy() { // Given: final String selectQuery = "SELECT col0, col1, col2 FROM test2 EMIT CHANGES;"; final PlanNode logicalPlan = buildLogicalPlan(selectQuery); initialSchemaKTable = buildSchemaKTableFromPlan(logicalPlan); final List<Expression> groupByExpressions = Arrays.as...
public static Object invokeMethod(Object target, Method method, Object... args) throws InvocationTargetException, IllegalArgumentException, SecurityException { while (true) { if (!method.isAccessible()) { method.setAccessible(true); } try { ...
@Test public void testInvokeMethod() throws NoSuchMethodException, InvocationTargetException { Assertions.assertEquals(0, ReflectionUtil.invokeMethod("", "length")); Assertions.assertEquals(3, ReflectionUtil.invokeMethod("foo", "length")); Assertions.assertThrows(NoSuchMetho...
@Override public Map<Uuid, Set<Integer>> partitions() { return partitions; }
@Test public void testAttributes() { Map<Uuid, Set<Integer>> partitions = mkAssignment( mkTopicAssignment(Uuid.randomUuid(), 1, 2, 3) ); Assignment assignment = new Assignment(partitions); assertEquals(partitions, assignment.partitions()); }
public static void writePositionToBlockBuilder(Block block, int position, BlockBuilder blockBuilder) { if (block instanceof DictionaryBlock) { position = ((DictionaryBlock) block).getId(position); block = ((DictionaryBlock) block).getDictionary(); } if (blockBuilder ...
@Test public void testMapBlockBuilder() { BlockBuilder blockBuilder1 = TEST_MAP_TYPE.createBlockBuilder(null, 1); BlockBuilder mapBlockBuilder = blockBuilder1.beginBlockEntry(); writeValuesToMapBuilder(mapBlockBuilder); Block expectedBlock = blockBuilder1.closeEntry().build(); ...
@SuppressWarnings("unchecked") public static PipelineIR configToPipelineIR(final List<SourceWithMetadata> sourcesWithMetadata, final boolean supportEscapes, ConfigVariableExpander cve) throws InvalidIRException { return compileSources(sourcesWithMetadata, supp...
@Test public void testConfigToPipelineIR() throws Exception { SourceWithMetadata swm = new SourceWithMetadata("proto", "path", 1, 1, "input {stdin{}} output{stdout{}}"); final ConfigVariableExpander cve = ConfigVariableExpander.withoutSecret(EnvironmentVariableProvider.defaultProvider()); fi...
@VisibleForTesting ExportResult<MediaContainerResource> exportOneDrivePhotos(TokensAndUrlAuthData authData, Optional<IdOnlyContainerResource> albumData, Optional<PaginationData> paginationData, UUID jobId) throws IOException { Optional<String> albumId = Optional.empty(); if (albumData.isPresent())...
@Test public void exportAlbumWithoutNextPage() throws IOException { // Setup MicrosoftDriveItem folderItem = setUpSingleAlbum(); when(driveItemsResponse.getDriveItems()).thenReturn(new MicrosoftDriveItem[] {folderItem}); when(driveItemsResponse.getNextPageLink()).thenReturn(null); StringPagination...
public WatermarkAssignerOperator( int rowtimeFieldIndex, WatermarkGenerator watermarkGenerator, long idleTimeout, ProcessingTimeService processingTimeService) { this.rowtimeFieldIndex = rowtimeFieldIndex; this.watermarkGenerator = watermarkGenerator; ...
@Test public void testWatermarkAssignerOperator() throws Exception { OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(0, WATERMARK_GENERATOR, -1); testHarness.getExecutionConfig().setAutoWatermarkInterval(50); long currentTime = 0; ...
public static String normalize(final String path) { return normalize(path, true); }
@Test public void testPathName() { { Path path = new Path(PathNormalizer.normalize( "/path/to/file/"), EnumSet.of(Path.Type.directory)); assertEquals("file", path.getName()); assertEquals("/path/to/file", path.getAbsolute()); } { ...
public static boolean containsLowerCase(final long word) { return applyLowerCasePattern(word) != 0; }
@Test void containsLowerCaseLong() { // given final byte[] asciiTable = getExtendedAsciiTable(); shuffleArray(asciiTable, random); // when for (int idx = 0; idx < asciiTable.length; idx += Long.BYTES) { final long value = getLong(asciiTable, idx); fin...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertTimestamp() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("TIMESTAMP WITHOUT TIME ZONE") .dataType("TIMESTAMP WITHOUT TIME ZONE") ...
public RequestConfig getDefaultRequestConfig() { return defaultRequestConfig; }
@Test void getDefaultRequestConfig_returns_config_provided_at_construction() { assertThat(configuredClient.getDefaultRequestConfig()).isEqualTo(defaultRequestConfigMock); }
@Override protected Map<String, ConfigValue> validateSourceConnectorConfig(SourceConnector connector, ConfigDef configDef, Map<String, String> config) { Map<String, ConfigValue> result = super.validateSourceConnectorConfig(connector, configDef, config); validateSourceConnectorExactlyOnceSupport(conf...
@Test public void testConnectorTransactionBoundaryValidation() { herder = exactlyOnceHerder(); Map<String, String> config = new HashMap<>(); config.put(SourceConnectorConfig.TRANSACTION_BOUNDARY_CONFIG, CONNECTOR.toString()); SourceConnector connectorMock = mock(SourceConnector.clas...
public String getName() { return name; }
@Test public void hasAName() throws Exception { assertThat(handler.getName()) .isEqualTo("handler"); }
public static <T> T loadData(Map<String, Object> config, T existingData, Class<T> dataCls) { try { String existingConfigJson = MAPPER.writeValueAsString(existingData); Map<String, Object> existingConfig = MAPPER.readValue(...
@Test public void testLoadReaderConfigurationData() { ReaderConfigurationData confData = new ReaderConfigurationData(); confData.setTopicName("unknown"); confData.setReceiverQueueSize(1000000); confData.setReaderName("unknown-reader"); Map<String, Object> config = new HashMap...
public MediaType detect(InputStream input, Metadata metadata) throws IOException { if (input == null) { return MediaType.OCTET_STREAM; } input.mark(offsetRangeEnd + length); try { int offset = 0; // Skip bytes at the beginning, using skip() or read()...
@Test public void testDetectStreamReadProblems() throws Exception { byte[] data = "abcdefghijklmnopqrstuvwxyz0123456789".getBytes(US_ASCII); MediaType testMT = new MediaType("application", "test"); Detector detector = new MagicDetector(testMT, data, null, false, 0, 0); // Deliberatel...
public List<String> all() { char[] chars = new char[MAX_CHAR_LENGTH]; List<String> value = depth(this.root, new ArrayList<String>(), chars, 0); return value; }
@Test public void all() throws Exception { TrieTree trieTree = new TrieTree(); trieTree.insert("ABC"); trieTree.insert("abC"); List<String> all = trieTree.all(); String result = ""; for (String s : all) { result += s + ","; System.out.println(s...
@Override public Path createFile(String filename) throws IOException { return createFile(filename, (InputStream) null); }
@Test void shouldThrowExceptionGivenFileAlreadyExist() throws IOException { String workingDirId = IdUtils.create(); TestWorkingDir workingDirectory = new TestWorkingDir(workingDirId, new LocalWorkingDir(Path.of("/tmp/sub/dir/tmp/"), workingDirId)); workingDirectory.createFile("folder/file.t...
public Path createTempFile(String suffix) throws IOException { String actualSuffix = StringUtils.isBlank(suffix) ? ".tmp" : suffix; final Path path = tempFileDir == null ? Files.createTempFile("apache-tika-", actualSuffix) : Files.createTempFile(tempFileDir, "apache-tika-", actualSuffix...
@Test public void testFileDeletion() throws IOException { Path tempFile; try (TemporaryResources tempResources = new TemporaryResources()) { tempFile = tempResources.createTempFile(); assertTrue(Files.exists(tempFile), "Temp file should exist while TempResources is used"); ...
@Override public void isNotEqualTo(@Nullable Object expected) { super.isNotEqualTo(expected); }
@Test public void isNotEqualTo_WithoutToleranceParameter_Success_Shorter() { assertThat(array(2.2f, 3.3f)).isNotEqualTo(array(2.2f)); }
@Override public Optional<Period> chooseBin(final List<Period> availablePeriods, final QueryExecutionStats stats) { return availablePeriods.stream() .filter(per -> matches(per, stats.effectiveTimeRange())) .findFirst(); }
@Test void testChoosesProperPeriod() { final Optional<Period> chosenPeriod = toTest.chooseBin( List.of(Period.days(1), Period.days(2), Period.days(3)), getQueryExecutionStats(42, AbsoluteRange.create( DateTime.now(DateTimeZone.UTC).minusDays(1).minusHo...
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void group_nodes_are_marked_maintenance_if_group_availability_too_low_by_orchestrator() { final ClusterFixture fixture = ClusterFixture .forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3)) .bringEntireClusterUp() .proposeStorageN...
public T add(String str) { requireNonNull(str, JVM_OPTION_NOT_NULL_ERROR_MESSAGE); String value = str.trim(); if (isInvalidOption(value)) { throw new IllegalArgumentException("a JVM option can't be empty and must start with '-'"); } checkMandatoryOptionOverwrite(value); options.add(value);...
@Test public void add_checks_against_mandatory_options_is_case_sensitive() { String[] optionOverrides = { randomPrefix, randomPrefix + randomAlphanumeric(1), randomPrefix + randomAlphanumeric(2), randomPrefix + randomAlphanumeric(3), randomPrefix + randomAlphanumeric(4), random...
@Override public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException { if (response.length == 1 && response[0] == OAuthBearerSaslClient.BYTE_CONTROL_A && errorMessage != null) { log.debug("Received %x01 response from client after it received our error"); ...
@Test public void illegalToken() throws Exception { byte[] bytes = saslServer.evaluateResponse(clientInitialResponse(null, true, Collections.emptyMap())); String challenge = new String(bytes, StandardCharsets.UTF_8); assertEquals("{\"status\":\"invalid_token\"}", challenge); }
public void consume() throws InterruptedException { var item = queue.take(); LOGGER.info("Consumer [{}] consume item [{}] produced by [{}]", name, item.id(), item.producer()); }
@Test void testConsume() throws Exception { final var queue = spy(new ItemQueue()); for (var id = 0; id < ITEM_COUNT; id++) { queue.put(new Item("producer", id)); } reset(queue); // Don't count the preparation above as interactions with the queue final var consumer = new Consumer("consumer"...
@Override public void deleteLevel(Long id) { // 校验存在 validateLevelExists(id); // 校验分组下是否有用户 validateLevelHasUser(id); // 删除 memberLevelMapper.deleteById(id); }
@Test public void testDeleteLevel_success() { // mock 数据 MemberLevelDO dbLevel = randomPojo(MemberLevelDO.class); memberlevelMapper.insert(dbLevel);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbLevel.getId(); // 调用 levelService.deleteLevel(id); // 校验数据不存在了...
private FederationResult(List<TargetResult> targetResults) { this.targetResults = targetResults; if (targetResults.stream().anyMatch(TargetResult::isMandatory)) targetsToWaitFor = targetResults.stream().filter(TargetResult::isMandatory) .collect(Collectors.toCollection(A...
@Test void testFederationResult() { assertTimeout(ImmutableSet.of(), 100, 200, 180); assertTimeout(ImmutableSet.of(), 480, 400, 400); assertTimeout(ImmutableSet.of("dsp1"), 260, 280, 220); assertTimeout(ImmutableSet.of("organic"), 520, 160, 16...
@Override public ObjectNode encode(KubevirtNetwork network, CodecContext context) { checkNotNull(network, "Kubevirt network cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(NETWORK_ID, network.networkId()) .put(TYPE, network.type().name(...
@Test public void testKubevirtNetworkEncode() { KubevirtHostRoute hostRoute1 = new KubevirtHostRoute(IpPrefix.valueOf("10.10.10.0/24"), IpAddress.valueOf("20.20.20.1")); KubevirtHostRoute hostRoute2 = new KubevirtHostRoute(IpPrefix.valueOf("20.20.20.0/24"), IpAddress....
public ElasticProfile find(String profileId) { return this.stream() .filter(elasticProfile -> elasticProfile.getId().equals(profileId)) .findFirst().orElse(null); }
@Test public void shouldFindProfileById() throws Exception { assertThat(new ElasticProfiles().find("foo"), is(nullValue())); ElasticProfile profile = new ElasticProfile("foo", "prod-cluster"); assertThat(new ElasticProfiles(profile).find("foo"), is(profile)); }
public Result<List<ConfigInfo>> getConfigList(ConfigInfo request, PluginType pluginType, boolean exactMatchFlag) { Result<?> result = checkConnection(request); if (!result.isSuccess()) { return new Result<>(result.getCode(), result.getMessage()); } String requestGroup = reque...
@Test public void getConfigList() { ConfigInfo configInfo = new ConfigInfo(); configInfo.setGroup(GROUP); configInfo.setKey(KEY); configInfo.setPluginType(PluginType.SPRINGBOOT_REGISTRY.getPluginName()); Result<List<ConfigInfo>> result = configService.getConfigList(configInfo...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 1) { if ("dateIntToTs".equals(methodName)) { return dateIntToTs(args[0]); } else if ("tsToDateInt".equals(methodName)) { return tsToDateInt(args[0]); } } else if (args.length == 2) { i...
@Test(expected = NumberFormatException.class) public void testInvalidCallIntsBetween() { SelUtilFunc.INSTANCE.call( "intsBetween", new SelType[] {SelString.of("foo"), SelLong.of(3), SelLong.of(1)}); }
@Udf(description = "Returns a masked version of the input string. The first n characters" + " will be replaced according to the default masking rules.") @SuppressWarnings("MethodMayBeStatic") // Invoked via reflection public String mask( @UdfParameter("input STRING to be masked") final String input, ...
@Test public void shouldMaskAllCharsIfLengthTooLong() { final String result = udf.mask("AbCd#$123xy Z", 999); assertThat(result, is("XxXx--nnnxx-X")); }
public String summarize(final ExecutionStep<?> step) { return summarize(step, "").summary; }
@Test public void shouldSummarizeWithSource() { // Given: final LogicalSchema schema = LogicalSchema.builder() .keyColumn(SystemColumns.ROWKEY_NAME, SqlTypes.STRING) .valueColumn(ColumnName.of("L1"), SqlTypes.STRING) .build(); final ExecutionStep<?> step = givenStep(StreamSelect.c...
public static boolean isBlank(final String value) { return StringUtils.isBlank(value); }
@Test public void testIsBlank() { assertTrue(JOrphanUtils.isBlank("")); assertTrue(JOrphanUtils.isBlank(null)); assertTrue(JOrphanUtils.isBlank(" ")); assertFalse(JOrphanUtils.isBlank(" zdazd dzd ")); }
@Override @Transactional(rollbackFor = Exception.class) public void syncCodegenFromDB(Long tableId) { // 校验是否已经存在 CodegenTableDO table = codegenTableMapper.selectById(tableId); if (table == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 从数据库中,获得数据库表结构...
@Test @Disabled // TODO @芋艿:这个单测会随机性失败,需要定位下; public void testSyncCodegenFromDB() { // mock 数据(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setTableName("t_yunai") .setDataSourceConfigId(1L).setScene(CodegenSceneEnum.ADMIN.getScene())); c...
@Override public void verify(byte[] data, byte[] signature, MessageDigest digest) { verify(data, new EcSignature(signature), digest); }
@Test public void shouldThrowValidationExceptionIfSignatureIsInvalid() { thrown.expect(VerificationException.class); thrown.expectMessage("Invalid signature"); verify(D.add(BigInteger.ONE), Q, "SHA-256"); }
public String namespaceProperties(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns), "properties"); }
@Test public void testNamespaceProperties() { Namespace ns = Namespace.of("ns"); assertThat(withPrefix.namespaceProperties(ns)) .isEqualTo("v1/ws/catalog/namespaces/ns/properties"); assertThat(withoutPrefix.namespaceProperties(ns)).isEqualTo("v1/namespaces/ns/properties"); }
public static void addMapPopulation(final Map<String, MethodDeclaration> toAdd, final BlockStmt body, final String mapName) { Map<String, Expression> toAddExpr = toAdd.entrySet().stream().collect(Collectors.toMap( Ma...
@Test void addMapPopulation() { final Map<String, MethodDeclaration> toAdd = IntStream.range(0, 5).boxed().collect(Collectors.toMap(index -> "KEY_" + index, index -> getMethodDeclaration("METHOD_" + index))); BlockStmt body = new BlockStmt(); String mapName = "MAP_NAME"; CommonCodege...
public void start() { if (running) throw new IllegalStateException(); start = ticks.ticks(); running = true; }
@Test void twiceStarted() { assertThrows(IllegalStateException.class, () -> { FakeTicks f = new FakeTicks(); Stopwatch s = new Stopwatch(f); s.start(); s.start(); }); }
@Override public ByteOrder getByteOrder() { return isBigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; }
@Test public void testGetByteOrder() { ByteArrayObjectDataOutput outLE = new ByteArrayObjectDataOutput(10, mockSerializationService, LITTLE_ENDIAN); ByteArrayObjectDataOutput outBE = new ByteArrayObjectDataOutput(10, mockSerializationService, BIG_ENDIAN); assertEquals(LITTLE_ENDIAN, outLE.g...
@Operation(summary = "downloadTaskLog", description = "DOWNLOAD_TASK_INSTANCE_LOG_NOTES") @Parameters({ @Parameter(name = "taskInstanceId", description = "TASK_ID", required = true, schema = @Schema(implementation = int.class, example = "100")) }) @GetMapping(value = "/download-log") @Respon...
@Test public void testDownloadTaskLog() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("taskInstId", "1501"); MvcResult mvcResult = mockMvc.perform(get("/log/download-log") .header("sessionId", sessionId) ...
public Map<String, String> penRequestAllowed(PenRequest request) throws PenRequestException, SharedServiceClientException { final List<PenRequestStatus> result = repository.findByBsnAndDocTypeAndSequenceNo(request.getBsn(), request.getDocType(), request.getSequenceNo()); checkIfTooSoonOrTooOften(result)...
@Test public void penRequestAllowedWithValidPreviousRequests() throws PenRequestException, SharedServiceClientException { // create three penRequests with a RequestDateTime, 24 hours apart PenRequestStatus firstStatus = new PenRequestStatus(); firstStatus.setRequestDatetime(LocalDateTime.of...
@SuppressWarnings("MethodLength") static void dissectControlRequest( final ArchiveEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); ...
@Test void controlRequestExtendRecording2() { internalEncodeLogHeader(buffer, 0, 12, 32, () -> 10_000_000_000L); final ExtendRecordingRequest2Encoder requestEncoder = new ExtendRecordingRequest2Encoder(); requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) ...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path file : files.keySet()) { callback.delete(file); final SMBSession.DiskShareWrapper share = session.openShare(file); ...
@Test public void testDeleteFileAndFolder() throws Exception { final Path home = new DefaultHomeFinderService(session).find(); final Path folder = new SMBDirectoryFeature(session).mkdir( new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), ...
@Override public Type field(StructField field, Type typeResult) { return typeResult; }
@Test public void testNestedTypeConversion() { Type converted = DeltaLakeDataTypeVisitor.visit( deltaNestedSchema, new DeltaLakeTypeToType(deltaNestedSchema)); Schema convertedSchema = new Schema(converted.asNestedType().asStructType().fields()); assertThat(convertedSchema.findType(IN...
@Override public void updateLevel(int level) { Preconditions.checkArgument( level >= 0 && level <= MAX_LEVEL, "level(" + level + ") must be non-negative and no more than " + MAX_LEVEL); Preconditions.checkArgument( level <= this.topLevel + 1, ...
@Test void testUpdateToNegativeLevel() { assertThatThrownBy(() -> heapHeadIndex.updateLevel(-1)) .isInstanceOf(IllegalArgumentException.class); }
@Override @SuppressWarnings("UseOfSystemOutOrSystemErr") public void run(Namespace namespace, Liquibase liquibase) throws Exception { final Set<Class<? extends DatabaseObject>> compareTypes = new HashSet<>(); if (isTrue(namespace.getBoolean("columns"))) { compareTypes.add(Column.cla...
@Test void testDumpSchema() throws Exception { dumpCommand.run(null, new Namespace(ATTRIBUTE_NAMES.stream() .collect(Collectors.toMap(a -> a, b -> true))), existedDbConf); final Element changeSet = getFirstElement(toXmlDocument(baos).getDocumentElement(), "changeSet"); assertCre...
public boolean shouldDropFrame(final InetSocketAddress address, final UnsafeBuffer buffer, final int length) { return false; }
@Test void shouldDropSingleFrameOnce() { final FixedLossGenerator fixedLossGenerator = new FixedLossGenerator(0, 0, 1408); assertTrue(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 0, 1408)); assertFalse(fixedLossGenerator.shouldDropFrame(null, null, 123, 456, 0, 0, 1408)); ...
@Override protected void write(final MySQLPacketPayload payload) { for (Object each : data) { if (null == each) { payload.writeInt1(NULL); continue; } writeDataIntoPayload(payload, each); } }
@Test void assertWrite() { long now = System.currentTimeMillis(); Timestamp timestamp = new Timestamp(now); MySQLTextResultSetRowPacket actual = new MySQLTextResultSetRowPacket(Arrays.asList(null, "value", BigDecimal.ONE, new byte[]{}, timestamp, Boolean.TRUE)); actual.write(payload)...
public long getMaxWeight() { return workerCacheBytes; }
@Test public void testMaxWeight() throws Exception { assertEquals(400 * MEGABYTES, cache.getMaxWeight()); }
@Override public String getMethod() { return PATH; }
@Test public void testGetChatMenuButtonAsDefault() { GetChatMenuButton getChatMenuButton = GetChatMenuButton .builder() .build(); assertEquals("getChatMenuButton", getChatMenuButton.getMethod()); assertDoesNotThrow(getChatMenuButton::validate); }
public static boolean isTmpFile(String uri) { String[] splits = StringUtils.splitByWholeSeparator(uri, TMP); if (splits.length < 2) { return false; } try { UUID.fromString(splits[splits.length - 1]); return true; } catch (IllegalArgumentException e) { return false; } }
@Test public void testIsTmpFile() { assertTrue(SegmentCompletionUtils.isTmpFile("hdfs://foo.tmp.550e8400-e29b-41d4-a716-446655440000")); assertFalse(SegmentCompletionUtils.isTmpFile("hdfs://foo.tmp.")); assertFalse(SegmentCompletionUtils.isTmpFile(".tmp.550e8400-e29b-41d4-a716-446655440000")); assertF...
@Override public void getErrors(ErrorCollection errors, String parentLocation) { String location = this.getLocation(parentLocation); if (new NameTypeValidator().isNameInvalid(name)) { errors.addError(location, NameTypeValidator.errorMessage("parameter", name)); } }
@Test public void shouldAddAnErrorIfParameterNameIsInvalid() { CRParameter crParameter = new CRParameter("#$$%@", null); ErrorCollection errorCollection = new ErrorCollection(); crParameter.getErrors(errorCollection, "TEST"); assertThat(errorCollection.getErrorsAsText()).contains("I...
protected Optional<BrokerData> findOneBroker(String topic) throws Exception { try { List<BrokerData> brokerDatas = topicRouteService.getAllMessageQueueView(ProxyContext.createForInner(this.getClass()), topic).getTopicRouteData().getBrokerDatas(); int skipNum = random.nextInt(brokerDatas....
@Test public void findOneBroker() { Set<String> resultBrokerNames = new HashSet<>(); // run 1000 times to test the random for (int i = 0; i < 1000; i++) { Optional<BrokerData> brokerData = null; try { brokerData = this.clusterMetadataService.findOneBr...
@Deprecated(forRemoval = true) @Nonnull protected static Path backwardsCompatible(@Nonnull Path path, NodeId nodeId, String configProperty) { final Path nodeIdSubdir = path.resolve(nodeId.getNodeId()); if(Files.exists(nodeIdSubdir) && Files.isDirectory(nodeIdSubdir)) { LOG.warn("Caut...
@Deprecated(forRemoval = true) @SuppressWarnings("removal") @Test void testBackwardsCompatibility(@TempDir Path tempDir) throws IOException { final Path withoutSubdir = DatanodeDirectories.backwardsCompatible(tempDir, new SimpleNodeId("5ca1ab1e-0000-4000-a000-000000000000"), "my_config_property"); ...
public BlobConfiguration getConfiguration() { return configuration; }
@Test void testHierarchicalBlobName() { context.getRegistry().bind("creds", storageSharedKeyCredential()); BlobEndpoint endpoint = (BlobEndpoint) context .getEndpoint( "azure-storage-blob://camelazure/container?blobName=blob/sub&credentials=#creds&credentialT...
public RowMetaAndData getRow() { RowMetaAndData row = new RowMetaAndData(); // First the type row.addValue( new ValueMetaString( "type" ), getTypeDesc() ); // The filename row.addValue( new ValueMetaString( "filename" ), file.getName().getBaseName() ); // The path row.addValue( new ValueM...
@Test public void testGetRow() throws KettleFileException, FileSystemException { File tempDir = new File( new TemporaryFolder().toString() ); FileObject tempFile = KettleVFS.createTempFile( "prefix", "suffix", tempDir.toString() ); Date timeBeforeFile = Calendar.getInstance().getTime(); ResultFile res...
@Override @MethodNotAvailable public void delete(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testDelete() { adapter.delete(23); }
public static boolean isProtobufClass(Class<?> pojoClazz) { if (protobufClss != null) { return protobufClss.isAssignableFrom(pojoClazz); } return false; }
@Test void testIsProtobufClass() { Assertions.assertTrue(ProtobufUtils.isProtobufClass(HelloRequest.class)); Assertions.assertTrue(ProtobufUtils.isProtobufClass(HelloReply.class)); Assertions.assertFalse(ProtobufUtils.isProtobufClass(Person.class)); Assertions.assertFalse(ProtobufUti...
public static SourceDescription create( final DataSource dataSource, final boolean extended, final List<RunningQuery> readQueries, final List<RunningQuery> writeQueries, final Optional<TopicDescription> topicDescription, final List<QueryOffsetSummary> queryOffsetSummaries, fina...
@Test public void shouldReturnSourceConstraints() { // Given: final String kafkaTopicName = "kafka"; final DataSource dataSource = buildDataSource(kafkaTopicName, Optional.empty()); // When final SourceDescription sourceDescription = SourceDescriptionFactory.create( dataSource, tr...
@Override public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { refreshClassLoader(classLoader); }
@Test void testStatus4() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ModuleModel moduleModel = applicationModel.newModule(); System.setProperty(CommonConstants.CLASS_DESERIALIZE_OPEN_CHECK, "false"); ...
public static NotControllerException newWrongControllerException(OptionalInt controllerId) { if (controllerId.isPresent()) { return new NotControllerException("The active controller appears to be node " + controllerId.getAsInt() + "."); } else { return new Not...
@Test public void testNewWrongControllerExceptionWithNoController() { assertExceptionsMatch(new NotControllerException("No controller appears to be active."), newWrongControllerException(OptionalInt.empty())); }
@Override public void publish(ScannerReportWriter writer) { AbstractProjectOrModule rootProject = moduleHierarchy.root(); ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder() .setAnalysisDate(projectInfo.getAnalysisDate().getTime()) // Here we want key without branch ...
@Test public void write_not_analysed_file_counts() { when(componentStore.getNotAnalysedFilesByLanguage()).thenReturn(ImmutableMap.of("c", 10, "cpp", 20)); underTest.publish(writer); ScannerReport.Metadata metadata = reader.readMetadata(); assertThat(metadata.getNotAnalyzedFilesByLanguageMap()).conta...
protected synchronized boolean download(final DownloadableFile downloadableFile) throws IOException, GeneralSecurityException { File toDownload = downloadableFile.getLocalFile(); LOG.info("Downloading {}", toDownload); String url = downloadableFile.url(urlGenerator); final HttpRequestBas...
@Test public void shouldThrowExceptionIfTheServerIsDown() { ServerBinaryDownloader downloader = new ServerBinaryDownloader(new GoAgentServerHttpClientBuilder(null, SslVerificationMode.NONE, null, null, null), ServerUrlGeneratorMother.generatorFor("locahost", server.getPort())); assertThatThrownBy(()...
static void handleJvmOptions(String[] args, String lsJavaOpts) { final JvmOptionsParser parser = new JvmOptionsParser(args[0]); final String jvmOpts = args.length == 2 ? args[1] : null; try { Optional<Path> jvmOptions = parser.lookupJvmOptionsFile(jvmOpts); parser.handleJ...
@Test public void testEnvironmentOPTSVariableTakesPrecedenceOverOptionsFile() throws IOException { String regex = "Xmx[^ ]+"; String expected = "Xmx25g"; File optionsFile = writeIntoTempOptionsFile(writer -> writer.println("-Xmx1g")); JvmOptionsParser.handleJvmOptions(new String[] {...
public void printKsqlEntityList(final List<KsqlEntity> entityList) { switch (outputFormat) { case JSON: printAsJson(entityList); break; case TABULAR: final boolean showStatements = entityList.size() > 1; for (final KsqlEntity ksqlEntity : entityList) { writer()....
@Test public void shouldPrintAssertNotExistsSchemaResult() { // Given: final KsqlEntityList entities = new KsqlEntityList(ImmutableList.of( new AssertSchemaEntity("statement", Optional.of("abc"), Optional.of(55), false) )); // When: console.printKsqlEntityList(entities); // Then: ...
void afterWrite(Runnable task) { for (int i = 0; i < WRITE_BUFFER_RETRIES; i++) { if (writeBuffer.offer(task)) { scheduleAfterWrite(); return; } scheduleDrainBuffers(); Thread.onSpinWait(); } // In scenarios where the writing threads cannot make progress then they at...
@Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY) public void afterWrite_drainFullWriteBuffer( BoundedLocalCache<Int, Int> cache, CacheContext context) { cache.drainStatus = PROCESSING_TO_IDLE; int[] queued = { 0 }; Runnable pendingTask = () -> queued[0]++; for (int i ...
@Override public void set(File file, String view, String attribute, Object value, boolean create) { throw unsettable(view, attribute, create); }
@Test public void testSet() { assertSetFails("unix:uid", 1); assertSetFails("unix:gid", 1); assertSetFails("unix:rdev", 1L); assertSetFails("unix:dev", 1L); assertSetFails("unix:ino", 1); assertSetFails("unix:mode", 1); assertSetFails("unix:ctime", 1L); assertSetFails("unix:nlink", 1);...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final List<Header> headers = new ArrayList<Header>(this.headers()); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status)...
@Test public void testReadRangeUnknownLength() throws Exception { final Path test = new DAVTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); final Local local = new Lo...
@Override public CapabilitySet requiredCapabilities(RequestView req) { Path pathMatcher = new Path(req.uri()); Route route = resolveRoute(pathMatcher); HandlerHolder<?> handler = resolveHandler(req.method(), route); return Optional.ofNullable(handler.config.requiredCapabilities) ...
@Test void resolves_correct_capabilities() { var restApi = RestApi.builder() .requiredCapabilities(Capability.CONTENT__METRICS_API) .addRoute(route("/api1") .requiredCapabilities(Capability.CONTENT__SEARCH_API) ...
public boolean isReservedIpAddress(String address) { if (StringUtils.isBlank(address)) { return false; } return ipBlocks.stream().anyMatch(e -> subnetContainsAddress(e, address)); }
@Test void testIsReservedIpAddress() { Assertions.assertTrue(ReservedIpChecker.getInstance().isReservedIpAddress("127.0.0.1")); Assertions.assertTrue(ReservedIpChecker.getInstance().isReservedIpAddress("192.168.1.10")); Assertions.assertFalse(ReservedIpChecker.getInstance().isReservedIpAddr...
public static String join(final char delimiter, final String... strings) { if (strings.length == 0) { return null; } if (strings.length == 1) { return strings[0]; } int length = strings.length - 1; for (final String s : strings) { if (s...
@Test public void testJoin() { assertNull(StringUtil.join('.')); assertEquals("Single part.", StringUtil.join('.', "Single part.")); assertEquals("part1.part2.p3", StringUtil.join('.', "part1", "part2", "p3")); assertEquals("E", StringUtil.join('E', new String[2])); }
@Override public void put(final Windowed<Bytes> sessionKey, final byte[] aggregate) { wrapped().put(sessionKey, aggregate); context.logChange(name(), SessionKeySchema.toBinary(sessionKey), aggregate, context.timestamp(), wrapped().getPosition()); }
@Test public void shouldLogPutsWithPosition() { final Bytes binaryKey = SessionKeySchema.toBinary(key1); when(inner.getPosition()).thenReturn(POSITION); store.put(key1, value1); verify(inner).put(key1, value1); verify(context).logChange(store.name(), binaryKey, value1, 0L, ...
public void setSha1sum(String sha1sum) { this.sha1sum = sha1sum; }
@Test public void testSetSha1sum() { String sha1sum = "test"; Dependency instance = new Dependency(); instance.setSha1sum(sha1sum); assertEquals(sha1sum, instance.getSha1sum()); }
public Collection<String> getAllLogicTables() { return shardingTables.keySet(); }
@Test void assertGetAllLogicTables() { assertThat(createBindingTableRule().getAllLogicTables(), is(new LinkedHashSet<>(Arrays.asList("logic_table", "sub_logic_table")))); }
public static void init() { initHandlers(); initChains(); initPaths(); initDefaultHandlers(); ModuleRegistry.registerModule(HandlerConfig.CONFIG_NAME, Handler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HandlerConfig.CONFIG_NAME), null); }
@Test public void mixedPathsAndSource() { Handler.config.setPaths(Arrays.asList( mkPathChain(null, "/my-api/first", "post", "third"), mkPathChain(MockEndpointSource.class.getName(), null, null, "secondBeforeFirst", "third"), mkPathChain(null, "/my-api/second", "put", "thi...
@Override protected JsonObject convert(final JsonObject data) { return data.getAsJsonObject(ConfigGroupEnum.RULE.name()); }
@Test public void testConvert() { JsonObject jsonObject = new JsonObject(); JsonObject expectJsonObject = new JsonObject(); jsonObject.add(ConfigGroupEnum.RULE.name(), expectJsonObject); assertThat(mockRuleDataRefresh.convert(jsonObject), is(expectJsonObject)); }
@SuppressWarnings("unchecked") public static <T> TypeInformation<T> createTypeInfo(Class<T> type) { return (TypeInformation<T>) createTypeInfo((Type) type); }
@Test void testCreateTypeInfoFromInstance() { ResultTypeQueryable instance = new ResultTypeQueryable<Long>() { @Override public TypeInformation<Long> getProducedType() { return BasicTypeInfo.LONG_TYPE_INFO; }...
public static <V> Read<V> read() { return new AutoValue_SparkReceiverIO_Read.Builder<V>().build(); }
@Test public void testReadFromCustomReceiverWithOffset() { CustomReceiverWithOffset.shouldFailInTheMiddle = false; ReceiverBuilder<String, CustomReceiverWithOffset> receiverBuilder = new ReceiverBuilder<>(CustomReceiverWithOffset.class).withConstructorArgs(); SparkReceiverIO.Read<String> reader = ...
@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 testMatchSchema() { run( "def dogSchema = { id: '#string', color: '#string' }", "def schema = ({ id: '#string', name: '#string', dog: '##(dogSchema)' })", "def response1 = { id: '123', name: 'foo' }", "match response1 == schema", ...
public static void main(String[] args) { // create model, view and controller var giant = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); var view = new GiantView(); var controller = new GiantController(giant, view); // initial display controller.updateView(); // contro...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public SchemaAndValue toConnectData(final String topic, final byte[] value) { if (this.schema == null) { throw new UnsupportedOperationException("ProtobufNoSRConverter is an internal " + "converter to ksqldb. It should not be instantiated via reflection through a no-arg " + "co...
@Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenUsedWithNoArgConstructor1() { // Given final ProtobufNoSRConverter protobufNoSRConverter = new ProtobufNoSRConverter(); // When protobufNoSRConverter.toConnectData("topic", "test".getBytes(StandardCharsets.UTF_8...
@Override public V get(Object key) { if (!underlyingMap.containsKey(key)) return null; B value = underlyingMap.get(key); return valueMapping.apply(value); }
@Test public void testGet() { Map<String, Integer> underlying = createTestMap(); TranslatedValueMapView<String, String, Integer> view = new TranslatedValueMapView<>(underlying, v -> v.toString()); assertEquals("2", view.get("foo")); assertEquals("3", view.get("bar")); ...
@Override public ObjectNode encode(LispNonceAddress address, CodecContext context) { checkNotNull(address, "LispListAddress cannot be null"); final ObjectNode result = context.mapper().createObjectNode() .put(NONCE, address.getNonce()); if (address.getAddress() != null) { ...
@Test public void testLispNonceAddressEncode() { LispNonceAddress address = new LispNonceAddress.Builder() .withNonce(NONCE) .withAddress(MappingAddresses.ipv4MappingAddress(ADDRESS)) .build(); ObjectNode addressJson = nonceAddressCodec.encode(address,...
@Override public void startTrackThread() { }
@Test public void startTrackThread() { mSensorsAPI.startTrackThread(); }
public static Optional<SnapshotPath> parse(Path path) { Path filename = path.getFileName(); if (filename == null) { return Optional.empty(); } String name = filename.toString(); boolean partial = false; boolean deleted = false; if (name.endsWith(PART...
@Test public void testInvalidSnapshotFilenames() { Path root = FileSystems.getDefault().getPath("/"); // Doesn't parse log files assertEquals(Optional.empty(), Snapshots.parse(root.resolve("00000000000000000000.log"))); // Doesn't parse producer snapshots assertEquals(Optiona...
public static <T> ReadFiles<T> readFiles(Class<T> recordClass) { return new AutoValue_ThriftIO_ReadFiles.Builder<T>().setRecordClass(recordClass).build(); }
@Test public void testReadFilesBinaryProtocol() { PCollection<TestThriftStruct> testThriftDoc = mainPipeline .apply(Create.of(THRIFT_DIR + "data").withCoder(StringUtf8Coder.of())) .apply(FileIO.matchAll()) .apply(FileIO.readMatches()) .apply(ThriftIO.readFi...
boolean isModified(Namespace namespace) { Release release = releaseService.findLatestActiveRelease(namespace); List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId()); if (release == null) { return hasNormalItems(items); } Map<String, String> releasedConfiguration = GSON.fr...
@Test public void testNamespaceAddItem() { long namespaceId = 1; Namespace namespace = createNamespace(namespaceId); Release release = createRelease("{\"k1\":\"v1\"}"); List<Item> items = Arrays.asList(createItem("k1", "v1"), createItem("k2", "v2")); when(releaseService.findLatestActiveRelease(n...
@Override public ParsedLine parse(final String line, final int cursor, final ParseContext context) { final ParsedLine parsed = delegate.parse(line, cursor, context); if (context != ParseContext.ACCEPT_LINE) { return parsed; } if (UnclosedQuoteChecker.isUnclosedQuote(line)) { throw new EO...
@Test public void shouldAcceptIfLineTerminated() { // Given: givenDelegateWillReturn(TERMINATED_LINE); // When: final ParsedLine result = parser.parse("what ever", 0, ParseContext.ACCEPT_LINE); // Then: assertThat(result, is(parsedLine)); }
public static List<Integer> buildQueryWithINClause(Configuration conf, List<String> queries, StringBuilder prefix, StringBuilder suffix, Collect...
@Test public void testBuildQueryWithINClause() throws Exception { List<String> queries = new ArrayList<>(); List<Integer> ret; StringBuilder prefix = new StringBuilder(); StringBuilder suffix = new StringBuilder(); // Note, this is a "real" query that depends on one of the metastore tables p...
public boolean statsEnabled() { return statsEnabled; }
@Test void abilityBuilderSetStatsEnabledTrueTest() { Ability statsEnabledAbility = DefaultBot.getDefaultBuilder().setStatsEnabled(true).build(); assertTrue(statsEnabledAbility.statsEnabled()); }
@Override public void replay( long offset, long producerId, short producerEpoch, CoordinatorRecord record ) throws RuntimeException { ApiMessageAndVersion key = record.key(); ApiMessageAndVersion value = record.value(); switch (key.version()) { ...
@Test public void testReplayOffsetCommit() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class); CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class); Coordina...
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoke(invoker, invocation, PROVIDER.equals(MetricsSupport.getSide(invocation))); }
@Test void testCollectDisabled() { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); filter.invoke(invoker, invocation); Map<String, MetricSample> metricsMap = getMetricsMap(); metricsMap.remove(MetricsKey.APPLICATION_METRIC_INFO.getName()); Assertion...
boolean matchWhen(URL url, Invocation invocation) { if (CollectionUtils.isEmptyMap(whenCondition)) { return true; } return doMatch(url, null, invocation, whenCondition, true); }
@Test void testRoute_methodRoute() { Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", "", new Class<?>[0], new Object[0]); // More than one methods, mismatch StateRouter router = new ConditionStateRouterFactory() .getRouter(String.class, getRouteUrl("...