focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static <P, R> FuncRt<P, R> uncheck(Func<P, R> expression) { return uncheck(expression, RuntimeException::new); }
@SuppressWarnings("ConstantConditions") @Test public void supplierTest() { File noFile = new File("./no-file"); try { //本行代码原本需要抛出受检查异常,现在只抛出运行时异常 CheckedUtil.uncheck(() -> new FileInputStream(noFile)).call(); } catch (Exception re) { assertTrue(re instanceof RuntimeException); } }
@Override public TypeDefinition build( ProcessingEnvironment processingEnv, ArrayType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); TypeMirror componentType = type.getComponentType(); TypeDefinition subTypeDefi...
@Test void testBuild() { buildAndAssertTypeDefinition(processingEnv, integersField, "int[]", "int", builder); buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder); buildAndAssertTypeDefinition( processingEnv, ...
public static TableSchema of(Column... columns) { return new AutoValue_TableSchema(Arrays.asList(columns)); }
@Test public void testParseEnum8() { Map<String, Integer> enumValues = ImmutableMap.of( "a", -1, "b", 0, "c", 42); assertEquals( ColumnType.enum8(enumValues), ColumnType.parse("Enum8('a' = -1, 'b' = 0, 'c' = 42)")); }
@Override public boolean next() { if (closed || !values.hasNext()) { currentValue = null; return false; } currentValue = values.next(); return true; }
@Test void assertNextForEmptyResultSet() { try (GeneratedKeysResultSet actual = new GeneratedKeysResultSet()) { assertFalse(actual.next()); } }
public TableInfo setEntityName(@NotNull String entityName) { this.entityName = entityName; setConvert(); return this; }
@Test void setEntityNameTest() { ConfigBuilder configBuilder; Assertions.assertTrue(new TableInfo(new ConfigBuilder(GeneratorBuilder.packageConfig(), dataSourceConfig, GeneratorBuilder.strategyConfig(), null, null, null), "user").setEntityName("UserEntity").isConvert()); Assertions.assertFal...
@Override public void onSwipeDown() {}
@Test public void testOnSwipeDown() { mUnderTest.onSwipeDown(); Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction); }
public BoundingBox extendDegrees(double verticalExpansion, double horizontalExpansion) { if (verticalExpansion == 0 && horizontalExpansion == 0) { return this; } else if (verticalExpansion < 0 || horizontalExpansion < 0) { throw new IllegalArgumentException("BoundingBox extend op...
@Test public void extendDegreesTest() { BoundingBox boundingBox1 = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE); BoundingBox boundingBox2 = new BoundingBox(MIN_LATITUDE - 1, MIN_LONGITUDE - 1, MAX_LATITUDE, MAX_LONGITUDE); BoundingBox boundingBox3...
public static CatalogTable buildWithConfig(Config config) { ReadonlyConfig readonlyConfig = ReadonlyConfig.fromConfig(config); return buildWithConfig(readonlyConfig); }
@Test public void testComplexSchemaParse() throws FileNotFoundException, URISyntaxException { String path = getTestConfigFile("/conf/complex.schema.conf"); Config config = ConfigFactory.parseFile(new File(path)); SeaTunnelRowType seaTunnelRowType = CatalogTableUtil.buildWithC...
@Override public NacosUser parseToken(String token) throws AccessException { if (!tokenMap.containsKey(token)) { Authentication authentication = jwtTokenManager.getAuthentication(token); String username = authentication.getName(); if (username == null || username.isEmpty(...
@Test void testParseToken() throws AccessException { assertNotNull(cachedJwtTokenManager.parseToken("token")); }
@Override public void write(int b) throws IOException { if (buffer.length <= bufferIdx) { flushInternalBuffer(); } buffer[bufferIdx] = (byte) b; ++bufferIdx; }
@Test void testFailingSecondaryWriteArrayFail() throws Exception { DuplicatingCheckpointOutputStream duplicatingStream = createDuplicatingStreamWithFailingSecondary(); testFailingSecondaryStream(duplicatingStream, () -> duplicatingStream.write(new byte[512])); }
public static Sensor recordLatenessSensor(final String threadId, final String taskId, final StreamsMetricsImpl streamsMetrics) { return avgAndMaxSensor( threadId, taskId, RECORD_LATENE...
@Test public void shouldGetRecordLatenessSensor() { final String operation = "record-lateness"; final String avgDescription = "The observed average lateness of records in milliseconds, measured by comparing the record timestamp with " + "the current stream time"; ...
@Override public String getURL( String hostname, String port, String databaseName ) throws KettleDatabaseException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append( "jdbc:databricks://" ); urlBuilder.append( hostname ); if ( StringUtils.isNotBlank( port ) ) { urlBuilder.append...
@Test( expected = KettleDatabaseException.class ) public void testNoPath() throws Exception { DatabaseMeta dbMeta = getDBMeta(); dbMeta.getURL(); }
@Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final TransferStatus that = (TransferStatus) o; return length == that.length && Objects.equals(offset...
@Test public void testEquals() { assertEquals(new TransferStatus(), new TransferStatus()); assertEquals(new TransferStatus().hashCode(), new TransferStatus().hashCode()); }
synchronized void addFunction(final KsqlScalarFunction ksqlFunction) { checkCompatible(ksqlFunction); udfIndex.addFunction(ksqlFunction); }
@Test public void shouldThrowExceptionIfAddingFunctionWithDifferentPath() { // When: final Exception e = assertThrows( KafkaException.class, () -> factory.addFunction(create( (params, args) -> STRING, ParamTypes.STRING, emptyList(), FunctionName....
public FileStoreInfo getFileStoreByName(String fsName) throws DdlException { try { return client.getFileStoreByName(fsName, serviceId); } catch (StarClientException e) { if (e.getCode() == StatusCode.NOT_EXIST) { return null; } throw new Dd...
@Test public void testGetFileStoreByName() throws StarClientException, DdlException { S3FileStoreInfo s3FsInfo = S3FileStoreInfo.newBuilder() .setRegion("region").setEndpoint("endpoint").build(); FileStoreInfo fsInfo = FileStoreInfo.newBuilder().setFsKey("test-fskey") ...
public Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> getInjectedFieldReferenceBeanMap() { Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> map = new HashMap<>(); for (Map.Entry<InjectionMetadata.InjectedElement, String> entry : injectedFieldReferenceBeanCache.entrySet()) { ...
@Test void testGetInjectedFieldReferenceBeanMap() { ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor(); Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> referenceBeanMap = beanPostProcessor.getInjectedFieldReferenceBeanMap(); ...
public static PipelineDataSourceConfiguration newInstance(final String type, final String param) { switch (type) { case StandardPipelineDataSourceConfiguration.TYPE: return new StandardPipelineDataSourceConfiguration(param); case ShardingSpherePipelineDataSourceConfigurat...
@Test void assertNewInstanceForStandardPipelineDataSourceConfiguration() { assertThat(PipelineDataSourceConfigurationFactory.newInstance(StandardPipelineDataSourceConfiguration.TYPE, "url: jdbc:mock://127.0.0.1/foo_db"), instanceOf(StandardPipelineDataSourceConfiguration.class)); }
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenMultiLineCell_parses() { String multiLineString = "a\na\na\na\na\na\na\na\na\nand"; Schema schema = Schema.builder().addStringField("a_string").addDoubleField("a_double").build(); assertEquals( multiLineString, CsvIOParseHelpers.parseCell(multiLineString, schema.getField("a_...
@VisibleForTesting TransMeta filterPrivateDatabases( TransMeta transMeta ) { Set<String> privateDatabases = transMeta.getPrivateDatabases(); if ( privateDatabases != null ) { // keep only private transformation databases for ( Iterator<DatabaseMeta> it = transMeta.getDatabases().iterator(); it.has...
@Test public void filterPrivateDatabasesWithOnePrivateDatabaseAndOneInUseTest() { IUnifiedRepository purMock = mock( IUnifiedRepository.class ); TransMeta transMeta = spy( TransMeta.class ); transMeta.setDatabases( getDummyDatabases() ); Set<String> privateDatabases = new HashSet<>( ); privateDat...
public ConfigTransformerResult transform(Map<String, String> configs) { Map<String, Map<String, Set<String>>> keysByProvider = new HashMap<>(); Map<String, Map<String, Map<String, String>>> lookupsByProvider = new HashMap<>(); // Collect the variables from the given configs that need transforma...
@Test public void testReplaceVariableNoPath() { ConfigTransformerResult result = configTransformer.transform(Collections.singletonMap(MY_KEY, "${test:testKey}")); Map<String, String> data = result.data(); Map<String, Long> ttls = result.ttls(); assertEquals(TEST_RESULT_NO_PATH, data....
protected boolean configDevice(DeviceId deviceId) { // Returns true if config was successful, false if not and a clean up is // needed. final Device device = deviceService.getDevice(deviceId); if (device == null || !device.is(IntProgrammable.class)) { return true; } ...
@Test public void testConfigSourceDevice() { reset(deviceService, hostService); Device device = getMockDevice(true, DEVICE_ID); IntProgrammable intProg = getMockIntProgrammable(true, false, false, false); setUpDeviceTest(device, intProg, true, false); IntObjective intObj = In...
@Operation(summary = "deleteProcessInstanceById", description = "DELETE_PROCESS_INSTANCE_BY_ID_NOTES") @Parameters({ @Parameter(name = "id", description = "PROCESS_INSTANCE_ID", required = true, schema = @Schema(implementation = int.class, example = "100")) }) @DeleteMapping(value = "/{id}") ...
@Test public void testDeleteProcessInstanceById() throws Exception { Map<String, Object> mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); Mockito.doNothing().when(processInstanceService).deleteProcessInstanceById(Mockito.any(), Mockito.anyInt()); MvcRe...
public static Color fromHex(String hex) { if (!hex.startsWith("#") && !hex.startsWith("0x")) { hex = "#" + hex; } if ((hex.length() <= 7 && hex.startsWith("#")) || (hex.length() <= 8 && hex.startsWith("0x"))) { try { return Color.decode(hex); } catch (NumberFormatException e) { ret...
@Test public void fromHex() { assertEquals(Color.BLACK, ColorUtil.fromHex("0x000000")); assertEquals(Color.BLACK, ColorUtil.fromHex("#000000")); assertEquals(Color.BLACK, ColorUtil.fromHex("000000")); assertEquals(Color.BLACK, ColorUtil.fromHex("0x0")); assertEquals(Color.BLACK, ColorUtil.fromHex("#0")); ...
public static String md5Hex(Consumer<MessageDigest> digestHandler) { return digestHex(md5::get, digestHandler); }
@Test @SneakyThrows public void test() { Set<String> check = ConcurrentHashMap.newKeySet(); for (int i = 0; i < 1000; i++) { new Thread(() -> check.add(DigestUtils.md5Hex("test"))) .start(); } Thread.sleep(1000); System.out.println(check);...
@Override public String toString() { return Numeric.toHexStringWithPrefixZeroPadded(value.getValue(), value.getBitSize() >> 2); }
@Test public void testToString() { assertEquals( new Address("52b08330e05d731e38c856c1043288f7d9744").toString(), ("0x00052b08330e05d731e38c856c1043288f7d9744")); assertEquals( new Address("0x00052b08330e05d731e38c856c1043288f7d9744").toString(), ...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConsumerGroupMember that = (ConsumerGroupMember) o; return memberEpoch == that.memberEpoch && previousMemberEpoch == that.previousMemberEpoch...
@Test public void testEquals() { Uuid topicId1 = Uuid.randomUuid(); Uuid topicId2 = Uuid.randomUuid(); ConsumerGroupMember member1 = new ConsumerGroupMember.Builder("member-id") .setMemberEpoch(10) .setPreviousMemberEpoch(9) .setInstanceId("instance-id") ...
@Override public void onPass(Context context, ResourceWrapper rw, DefaultNode param, int count, Object... args) throws Exception { for (MetricExtension m : MetricExtensionProvider.getMetricExtensions()) { if (m instanceof AdvancedMetricExtension) { ((AdvancedMetricExtensi...
@Test public void onPass() throws Exception { FakeMetricExtension extension = new FakeMetricExtension(); FakeAdvancedMetricExtension advancedExtension = new FakeAdvancedMetricExtension(); MetricExtensionProvider.addMetricExtension(extension); MetricExtensionProvider.addMetricExtensio...
public abstract void renameTable(String dbName, String oldName, String newName) throws HCatException;
@Test public void testRenameTable() throws Exception { HCatClient client = HCatClient.create(new Configuration(hcatConf)); String tableName = "temptable"; String newName = "mytable"; client.dropTable(null, tableName, true); client.dropTable(null, newName, true); ArrayList<HCatFieldSchema> cols...
public void logNewElection( final int memberId, final long leadershipTermId, final long logPosition, final long appendPosition, final String reason) { final int length = ClusterEventEncoder.newElectionLength(reason); final int captureLength = captureLength(len...
@Test void logNewElection() { final int memberId = 42; final long leadershipTermId = 8L; final long logPosition = 9827342L; final long appendPosition = 342384382L; final String reason = "why an election was started"; final int offset = 16; logBuffer.putLon...
@Override public Optional<E> find(String name) { return entryMap.find(name); }
@Test public void shouldOnlyFindRegisteredObjects() { TestRegistry testRegistry = new TestRegistry(); assertThat(testRegistry.find("test")).isEmpty(); testRegistry.entryMap.putIfAbsent("test", "value"); assertThat(testRegistry.find("test")).contains("value"); }
public static Path getStagingDir(Cluster cluster, Configuration conf) throws IOException, InterruptedException { UserGroupInformation user = UserGroupInformation.getLoginUser(); return getStagingDir(cluster, conf, user); }
@Test public void testDirPermission() throws Exception { Cluster cluster = mock(Cluster.class); HdfsConfiguration conf = new HdfsConfiguration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "700"); MiniDFSCluster dfsCluster = null; try { dfsCluster = new MiniDFSCluster.Builder...
public static int ringNextIntByObj(Object object, AtomicInteger atomicInteger) { Assert.notNull(object); int modulo = CollUtil.size(object); return ringNextInt(modulo, atomicInteger); }
@Test public void ringNextIntByObjTest() { final AtomicInteger atomicInteger = new AtomicInteger(); // 开启并发测试,每个线程获取到的元素都是唯一的 ThreadUtil.concurrencyTest(strList.size(), () -> { final int index = RingIndexUtil.ringNextIntByObj(strList, atomicInteger); final String s = strList.get(index); assertNotNull(s)...
public WatsonxAiRequest request(Prompt prompt) { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder().build(); if (this.defaultOptions != null) { options = ModelOptionsUtils.merge(options, this.defaultOptions, WatsonxAiChatOptions.class); } if (prompt.getOptions() != null) { if (prompt.getOpti...
@Test public void testCreateRequestSuccessfullyWithChatDisabled() { String msg = "Test message"; WatsonxAiChatOptions modelOptions = WatsonxAiChatOptions.builder() .withModel("meta-llama/llama-2-70b-chat") .withDecodingMethod("sample") .withTemperature(0.1f) .withTopP(0.2f) .withTopK(10) .withM...
@Override public boolean mkdirs(Path f) throws IOException { return fs.mkdirs(f); }
@Test public void testRenameFileIntoDir() throws Exception { Path srcPath = new Path(TEST_ROOT_DIR, "testRenameSrc"); Path dstPath = new Path(TEST_ROOT_DIR, "testRenameDir"); localFs.mkdirs(dstPath); verifyRename(srcPath, dstPath, true); }
public Point getCenter() { return new Point(getCenterX(), getCenterY()); }
@Test public void getCenterTest() { Rectangle rectangle = create(1, 2, 3, 4); Assert.assertEquals(new Point(2, 3), rectangle.getCenter()); }
public String convert(ILoggingEvent event) { StringBuilder sb = new StringBuilder(); int pri = facility + LevelToSyslogSeverity.convert(event); sb.append("<"); sb.append(pri); sb.append(">"); sb.append(computeTimeStampString(event.getTimeStamp())); sb.append(' '); sb.append(localHost...
@Test public void datesLessThanTen() { // RFC 3164, section 4.1.2: // If the day of the month is less than 10, then it MUST be represented as // a space and then the number. For example, the 7th day of August would be // represented as "Aug 7", with two spaces between the "g" and the "7". Loggin...
@Override public boolean archive(String gcsUrl, byte[] data) { BlobInfo blobInfo = parseBlobInfo(gcsUrl); if (data.length <= options.chunkUploadThresholdInBytes) { // Create the blob in one request. logger.atInfo().log("Archiving data to GCS at '%s' in one request.", gcsUrl); storage.create...
@Test public void archive_withSmallSizeString_createsBlobInOneRequest() { GoogleCloudStorageArchiver archiver = archiverFactory.create(mockStorage); String dataToArchive = "TEST DATA"; boolean succeeded = archiver.archive(buildGcsUrl(BUCKET_ID, OBJECT_ID), dataToArchive); assertThat(succeeded).isTru...
@Override public void checkDone() throws IllegalStateException { boolean done = shouldStop || streamProgress.getCloseStream() != null || streamProgress.isFailToLock(); Preconditions.checkState(done, "There's more work to be done"); }
@Test public void testDoneOnFailToLockTrue() { StreamProgress streamProgress = new StreamProgress(); streamProgress.setFailToLock(true); ReadChangeStreamPartitionProgressTracker tracker = new ReadChangeStreamPartitionProgressTracker(streamProgress); tracker.checkDone(); }
static Set<String> getConfigValueAsSet(ServiceConfiguration conf, String configProp) { String value = getConfigValueAsStringImpl(conf, configProp); if (StringUtils.isBlank(value)) { log.info("Configuration for [{}] is the empty set.", configProp); return Collections.emptySet(); ...
@Test public void testGetConfigValueAsSetReturnsEmptySetIfMissing() { Properties props = new Properties(); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); Set<String> actual = ConfigUtils.getConfigValueAsSet(config, "prop1"); assertEqual...
public static Future<Integer> authTlsHash(SecretOperator secretOperations, String namespace, KafkaClientAuthentication auth, List<CertSecretSource> certSecretSources) { Future<Integer> tlsFuture; if (certSecretSources == null || certSecretSources.isEmpty()) { tlsFuture = Future.succeededFutu...
@Test void testAuthTlsHashScramSha512SecretFoundAndPasswordNotFound() { SecretOperator secretOperator = mock(SecretOperator.class); Map<String, String> data = new HashMap<>(); data.put("passwordKey", "my-password"); Secret secret = new Secret(); secret.setData(data); ...
public abstract byte[] encode(MutableSpan input);
@Test void span_64bitTraceId_JSON_V2() { clientSpan.traceId(clientSpan.traceId().substring(16)); assertThat(new String(encoder.encode(clientSpan), UTF_8)) .isEqualTo( "{\"traceId\":\"216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d50f68b\",\"kind\":\"CLIENT\",\"name\...
@Override public String authenticate(AuthenticationDataSource authData) throws AuthenticationException { SocketAddress clientAddress; String roleToken; ErrorCode errorCode = ErrorCode.UNKNOWN; try { if (authData.hasDataFromPeer()) { clientAddress = authDa...
@Test public void testAuthenticateSignedTokenWithDifferentDomain() throws Exception { List<String> roles = new ArrayList<String>() { { add("test_role"); } }; RoleToken token = new RoleToken.Builder("Z1", "invalid", roles).principal("test_app").build()...
public ReencryptionPendingInodeIdCollector getTraverser() { return traverser; }
@Test public void testThrottleAccumulatingTasks() throws Exception { final Configuration conf = new Configuration(); final ReencryptionHandler rh = mockReencryptionhandler(conf); // mock tasks piling up final Map<Long, ReencryptionUpdater.ZoneSubmissionTracker> submissions = new HashMap<>(); ...
public List<GrantDTO> getForTarget(GRN target) { return db.find(DBQuery.is(GrantDTO.FIELD_TARGET, target.toString())).toArray(); }
@Test @MongoDBFixtures("grants.json") public void getForTarget() { final GRN stream1 = grnRegistry.parse("grn::::stream:54e3deadbeefdeadbeef0000"); final GRN stream2 = grnRegistry.parse("grn::::stream:54e3deadbeefdeadbeef0001"); assertThat(dbService.getForTarget(stream1)).hasSize(1); ...
public static <T> void update(Map<String, String> properties, T obj) throws IllegalArgumentException { Field[] fields = obj.getClass().getDeclaredFields(); Arrays.stream(fields).forEach(f -> { if (properties.containsKey(f.getName())) { try { f.setAccessibl...
@Test public void testWithBlankVallueConfig() { Map<String, String> properties = new HashMap<>(); properties.put("name", " config "); properties.put("stringStringMap", "key1=value1 , key2= value2 "); properties.put("stringIntMap", "key1 = 1, key2 = 2 "); properties.pu...
@Override public void handlerPlugin(final PluginData pluginData) { if (null != pluginData && pluginData.getEnabled()) { SofaRegisterConfig sofaRegisterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), SofaRegisterConfig.class); if (Objects.isNull(sofaRegisterConfig)) ...
@Test public void testPluginDisable() { PluginData pluginData = new PluginData("", "", registryConfig, "1", false, null); sofaPluginDataHandler.handlerPlugin(pluginData); assertNull(Singleton.INST.get(SofaRegisterConfig.class)); }
@Override public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) { return Optional.empty(); }
@Test void getDevOpsProjectCreator_withCharacteristics_returnsEmpty() { assertThat(underTest.getDevOpsProjectCreator(mock(DbSession.class), Map.of())).isEmpty(); }
public static Extension findExtensionAnnotation(Class<?> clazz) { if (clazz.isAnnotationPresent(Extension.class)) { return clazz.getAnnotation(Extension.class); } // search recursively through all annotations for (Annotation annotation : clazz.getAnnotations()) { ...
@Test public void findExtensionAnnotation() { List<JavaFileObject> generatedFiles = JavaSources.compileAll(JavaSources.Greeting, JavaSources.WhazzupGreeting); assertEquals(2, generatedFiles.size()); Map<String, Class<?>> loadedClasses = new JavaFileObjectClassLoader().load(generatedFiles); ...
public static ByteBuffer getByteBufferOrNull(String property, JsonNode node) { if (!node.has(property) || node.get(property).isNull()) { return null; } JsonNode pNode = node.get(property); Preconditions.checkArgument( pNode.isTextual(), "Cannot parse byte buffer from non-text value: %s: %...
@Test public void getByteBufferOrNull() throws JsonProcessingException { assertThat(JsonUtil.getByteBufferOrNull("x", JsonUtil.mapper().readTree("{}"))).isNull(); assertThat(JsonUtil.getByteBufferOrNull("x", JsonUtil.mapper().readTree("{\"x\": null}"))) .isNull(); byte[] bytes = new byte[] {1, 2,...
@Override @Nullable public Object convert(String value) { if (value == null || value.isEmpty()) { return null; } final Parser parser = new Parser(timeZone.toTimeZone()); final List<DateGroup> r = parser.parse(value); if (r.isEmpty() || r.get(0).getDates().is...
@Test public void convertObeysTimeZone() throws Exception { Converter c = new FlexibleDateConverter(ImmutableMap.<String, Object>of("time_zone", "+12:00")); final DateTime dateOnly = (DateTime) c.convert("2014-3-12"); assertThat(dateOnly.getZone()).isEqualTo(DateTimeZone.forOffsetHours(12))...
private Resource assignContainer( FSSchedulerNode node, PendingAsk pendingAsk, NodeType type, boolean reserved, SchedulerRequestKey schedulerKey) { // How much does this request need? Resource capability = pendingAsk.getPerAllocationResource(); // How much does the node have? Resource avai...
@Test public void testNoNextPendingAsk() { FSLeafQueue queue = Mockito.mock(FSLeafQueue.class); ApplicationAttemptId applicationAttemptId = createAppAttemptId(1, 1); RMContext rmContext = Mockito.mock(RMContext.class); ConcurrentMap<ApplicationId, RMApp> rmApps = new ConcurrentHashMap<>(); RMApp r...
public void destroy() { boolean invokeDestroyed = false; this.lock.lock(); try { if (this.destroyed) { return; } this.destroyed = true; if (!this.running) { invokeDestroyed = true; } if (this....
@Test public void testDestroy() throws Exception { this.timer.start(); assertEquals(0, this.timer.destroyed.get()); Thread.sleep(100); this.timer.destroy(); assertEquals(1, this.timer.destroyed.get()); }
public static MembersView createNew(int version, Collection<MemberImpl> members) { List<MemberInfo> list = new ArrayList<>(members.size()); for (MemberImpl member : members) { list.add(new MemberInfo(member)); } return new MembersView(version, unmodifiableList(list)); }
@Test public void createNew() { int version = 7; MemberImpl[] members = MemberMapTest.newMembers(5); MembersView view = MembersView.createNew(version, Arrays.asList(members)); assertEquals(version, view.getVersion()); assertMembersViewEquals(members, view); }
public synchronized ConnectionProfile createGCSDestinationConnectionProfile( String connectionProfileId, String gcsBucketName, String gcsRootPath) { checkArgument( !Strings.isNullOrEmpty(connectionProfileId), "connectionProfileId can not be null or empty"); checkArgument(!Strings.isNullOrE...
@Test public void testCreateGCSDestinationConnectionShouldCreateSuccessfully() throws ExecutionException, InterruptedException { ConnectionProfile connectionProfile = ConnectionProfile.getDefaultInstance(); when(datastreamClient .createConnectionProfileAsync(any(CreateConnectionProfileReques...
@Override public boolean execute(String sql) throws SQLException { this.targetSQL = sql; return ExecuteTemplate.execute(this, (statement, args) -> statement.execute((String) args[0]), sql); }
@Test public void testExecute() throws SQLException { String sql = "select * from table_statment_proxy"; Assertions.assertNotNull(statementProxy.executeQuery(sql)); Assertions.assertDoesNotThrow(() -> statementProxy.executeUpdate(sql)); Assertions.assertDoesNotThrow(() -> statementPr...
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: ret...
@Test public void testConvertTypeCaseVarchar() { VarcharTypeInfo varcharTypeInfo = TypeInfoFactory.getVarcharTypeInfo(20); Type result = EntityConvertUtils.convertType(varcharTypeInfo); Type expectedType = ScalarType.createVarcharType(20); assertEquals(expectedType, result); }
public static PositionBound unbounded() { return new PositionBound(Position.emptyPosition()); }
@Test public void shouldEqualUnbounded() { final PositionBound bound1 = PositionBound.unbounded(); final PositionBound bound2 = PositionBound.unbounded(); assertEquals(bound1, bound2); }
@Override public ProcessConfigurable<?> toSink(Sink<T> sink) { DataStreamV2SinkTransformation<T, T> sinkTransformation = StreamUtils.addSinkOperator(this, sink, getType()); return StreamUtils.wrapWithConfigureHandle( new NonKeyedPartitionStreamImpl<>(environment, sink...
@Test void testToSink() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); GlobalStreamImpl<Integer> stream = new GlobalStreamImpl<>(env, new TestingTransformation<>("t1", Types.INT, 1)); stream.toSink(DataStreamV2SinkUtils.wrapSink(new DiscardingSink...
public static MediaType valueOf(String contentType) { if (StringUtils.isEmpty(contentType)) { throw new IllegalArgumentException("MediaType must not be empty"); } String[] values = contentType.split(";"); String charset = Constants.ENCODE; for (String value : values) ...
@Test void testValueOf() { MediaType mediaType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED); String type = "application/x-www-form-urlencoded"; String charset = "UTF-8"; assertEquals(type, mediaType.getType()); assertEquals(charset, mediaType.getCharset()); ...
public void moveModel(int fromPosition, int toPosition) { assertNotBuildingModels(); adapter.moveModel(fromPosition, toPosition); requestDelayedModelBuild(500); }
@Test public void moveModel() { AdapterDataObserver observer = mock(AdapterDataObserver.class); final List<TestModel> testModels = new ArrayList<>(); testModels.add(new TestModel(1)); testModels.add(new TestModel(2)); testModels.add(new TestModel(3)); EpoxyController controller = new EpoxyCon...
@InvokeOnHeader(Web3jConstants.ETH_GET_BALANCE) void ethGetBalance(Message message) throws IOException { String address = message.getHeader(Web3jConstants.ADDRESS, configuration::getAddress, String.class); DefaultBlockParameter atBlock = toDefaultBlockParameter(message.getHeader(Web3...
@Test public void ethGetBalanceTest() throws Exception { EthGetBalance response = Mockito.mock(EthGetBalance.class); Mockito.when(mockWeb3j.ethGetBalance(any(), any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getBalance()).thenRet...
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testReplaceOldValueFail() { RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simple"); map.put(new SimpleKey("1"), new SimpleValue("2")); boolean res = map.replace(new SimpleKey("1"), new SimpleValue("43"), new SimpleValue("31")); Assertion...
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData, TypeReference<T> responseFormat) { return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null); }
@Test public void testNullMethod() { RestClient client = spy(new RestClient(null)); assertThrows(NullPointerException.class, () -> client.httpRequest( MOCK_URL, null, null, TEST_DTO, TEST_TYPE, MOCK_SECRE...
ControllerResult<AssignReplicasToDirsResponseData> handleAssignReplicasToDirs(AssignReplicasToDirsRequestData request) { if (!featureControl.metadataVersion().isDirectoryAssignmentSupported()) { throw new UnsupportedVersionException("Directory assignment is not supported yet."); } in...
@Test void testHandleAssignReplicasToDirs() { ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().build(); Uuid dir1b1 = Uuid.fromString("hO2YI5bgRUmByNPHiHxjNQ"); Uuid dir2b1 = Uuid.fromString("R3Gb1HLoTzuKMgAkH5Vtpw"); Uuid dir1b2 = Uuid.fromString("TBGa...
public Optional<String> getIPAddr() { if (this == DiscoveryResult.EMPTY) { return Optional.empty(); } if (server.getInstanceInfo() != null) { String ip = server.getInstanceInfo().getIPAddr(); if (ip != null && !ip.isEmpty()) { return Optional.o...
@Test void ipAddrEmptyForIncompleteInstanceInfo() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("ipAddrMissing") .setHostName("ipAddrMissing") .setPort(7777) .build(); final DiscoveryEnabledServer server = new Di...
@Override public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config) throws InvalidRequestEventException { // Expect the HTTP method and context to be populated. If they are not, we are handling an // uns...
@Test void readRequest_invalidEventEmptyContext_expectException() { try { AwsProxyRequest req = new AwsProxyRequestBuilder("/path", "GET").build(); req.setRequestContext(null); reader.readRequest(req, null, null, ContainerConfig.defaultConfig()); fail("Expecte...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldIncludePathForErrorsInRootNode() { // Given: final KsqlJsonDeserializer<Double> deserializer = givenDeserializerForSchema(Schema.OPTIONAL_FLOAT64_SCHEMA, Double.class); final byte[] bytes = serializeJson(BooleanNode.valueOf(true)); // When: final Exception e = as...
@Override public ListShareGroupsResult listShareGroups(ListShareGroupsOptions options) { final KafkaFutureImpl<Collection<Object>> all = new KafkaFutureImpl<>(); final long nowMetadata = time.milliseconds(); final long deadline = calcDeadlineMs(nowMetadata, options.timeoutMs()); runn...
@Test public void testListShareGroups() throws Exception { try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(4, 0), AdminClientConfig.RETRIES_CONFIG, "2")) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); // Empty metadata resp...
@Override public Stream<HoodieInstant> getCandidateInstants(HoodieTableMetaClient metaClient, HoodieInstant currentInstant, Option<HoodieInstant> lastSuccessfulInstant) { HoodieActiveTimeline activeTimeline = metaClient.reloadActiveTimeline(); if (Clustering...
@Test public void testConcurrentWritesWithInterleavingCompaction() throws Exception { createCommit(metaClient.createNewInstantTime(), metaClient); HoodieActiveTimeline timeline = metaClient.getActiveTimeline(); // consider commits before this are all successful Option<HoodieInstant> lastSuccessfulInst...
@Override public String getXML() { StringBuilder retval = new StringBuilder( 1500 ); retval.append( " " ).append( XMLHandler.addTagValue( "accept_filenames", inputFiles.acceptingFilenames ) ); retval.append( " " ).append( XMLHandler.addTagValue( "passing_through_fields", inputFiles.passingThruField...
@Test public void testGetXmlWorksIfWeUpdateOnlyPartOfInputFilesInformation() { inputMeta.inputFiles = new BaseFileInputFiles(); inputMeta.inputFiles.fileName = new String[] { FILE_NAME_VALID_PATH }; inputMeta.getXML(); assertEquals( inputMeta.inputFiles.fileName.length, inputMeta.inputFiles.fileMask...
public void execute() { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas)) .visit(treeRootHolder.getReportTreeRoot()); }
@Test public void compute_duplicated_lines_counts_lines_from_original_and_ignores_InProjectDuplicate() { TextBlock original = new TextBlock(1, 1); duplicationRepository.addDuplication(FILE_1_REF, original, FILE_2_REF, new TextBlock(2, 2)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLI...
public static String translateTableName(String tableName, @Nullable String databaseName, boolean ignoreCase) { Preconditions.checkArgument(StringUtils.isNotEmpty(tableName), "'tableName' cannot be null or empty"); String[] tableSplit = StringUtils.split(tableName, '.'); switch (tableSplit.length) { ca...
@Test public void translateTableNameTest() { // valid cases with non-default database check(LOGICAL_TABLE_NAME, DATABASE_NAME, FULLY_QUALIFIED_TABLE_NAME); check(FULLY_QUALIFIED_TABLE_NAME, DATABASE_NAME, FULLY_QUALIFIED_TABLE_NAME); check(FULLY_QUALIFIED_TABLE_NAME, null, FULLY_QUALIFIED_TABLE_NAME);...
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query));...
@Test public void filter_on_projectUuids_if_projectUuid_is_non_empty_and_criteria_empty() { ProjectMeasuresQuery query = newProjectMeasuresQuery(emptyList(), Collections.singleton("foo")); assertThat(query.getProjectUuids()).isPresent(); }
public String[] getUrlStrings() { String[] fileStrings = new String[ files.size() ]; for ( int i = 0; i < fileStrings.length; i++ ) { fileStrings[ i ] = Const.optionallyDecodeUriString( files.get( i ).getPublicURIString() ); } return fileStrings; }
@Test public void testGetUrlStrings() throws Exception { String sFileA = "hdfs://myfolderA/myfileA.txt"; String sFileB = "file:///myfolderB/myfileB.txt"; FileObject fileA = mock( FileObject.class ); FileObject fileB = mock( FileObject.class ); when( fileA.getPublicURIString() ).thenReturn( sFile...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(containerService.isContainer(folder)) { final Storage.Buckets.Insert request = session.getClient().buckets().insert(session.getHost().getCredentials().getUsername(), ...
@Test public void testDirectoryDeleteWithVersioning() throws Exception { final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path parent = new GoogleStorageDirectoryFeature(session).mkdir(new Path(bucket, new AlphanumericRandomS...
@VisibleForTesting static StringStatistics toStringStatistics(HiveWriterVersion hiveWriterVersion, DwrfProto.StringStatistics stringStatistics, boolean isRowGroup) { if (hiveWriterVersion == ORIGINAL && !isRowGroup) { return null; } Slice maximum = stringStatistics.hasMaximu...
@Test public void testToStringStatistics() { // ORIGINAL version only produces stats at the row group level assertNull(DwrfMetadataReader.toStringStatistics( HiveWriterVersion.ORIGINAL, DwrfProto.StringStatistics.newBuilder() .setMinimum("a...
@VisibleForTesting Path getJarArtifact() throws IOException { Optional<String> classifier = Optional.empty(); Path buildDirectory = Paths.get(project.getBuild().getDirectory()); Path outputDirectory = buildDirectory; // Read <classifier> and <outputDirectory> from maven-jar-plugin. Plugin jarPlug...
@Test public void testGetJarArtifact_relativeOutputDirectoryFromJarPlugin() throws IOException { when(mockMavenProject.getBasedir()).thenReturn(new File("/base/dir")); when(mockBuild.getDirectory()).thenReturn(temporaryFolder.getRoot().toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1")...
@Override public void build(T instance) { super.build(instance); if (!StringUtils.isEmpty(version)) { instance.setVersion(version); } if (!StringUtils.isEmpty(group)) { instance.setGroup(group); } if (deprecated != null) { instance...
@Test void tag() { ServiceBuilder builder = new ServiceBuilder(); builder.tag("tag"); Assertions.assertEquals("tag", builder.build().getTag()); }
@Override public void alterJob(AlterLoadStmt stmt) throws DdlException { writeLock(); try { if (stmt.getAnalyzedJobProperties().containsKey(LoadStmt.PRIORITY)) { priority = LoadPriority.priorityByName(stmt.getAnalyzedJobProperties().get(LoadStmt.PRIORITY)); ...
@Test public void testAlterLoad(@Injectable LoadStmt loadStmt, @Injectable AlterLoadStmt alterLoadStmt, @Injectable DataDescription dataDescription, @Injectable LabelName labelName, @Injectable Da...
Optional<List<ComparisonDifference>> registeredComparisonDifferencesOf(DualValue dualValue) { return this.dualValues.stream() // use sameValues to get already visited dual values with different location .filter(visitedDualValue -> visitedDualValue.dualValue.sameVa...
@Test void should_return_empty_optional_for_unknown_dual_values() { // GIVEN VisitedDualValues visitedDualValues = new VisitedDualValues(); DualValue dualValue = new DualValue(list(""), "abc", "abc"); // WHEN Optional<List<ComparisonDifference>> optionalComparisonDifferences = visitedDualValues.re...
@Override public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException { try (Connection connection = material.getDataSource().getConnection()) { Collection<String> schemaNames = SchemaMetaDataLoader.loadSchemaNames(connection, TypedSPILoader.getService(Datab...
@Test void assertLoadWithTables() throws SQLException { DataSource dataSource = mockDataSource(); ResultSet schemaResultSet = mockSchemaMetaDataResultSet(); when(dataSource.getConnection().getMetaData().getSchemas()).thenReturn(schemaResultSet); ResultSet tableResultSet = mockTableMe...
@Operation(summary = "deleteResource", description = "DELETE_RESOURCE_BY_ID_NOTES") @Parameters({ @Parameter(name = "fullName", description = "RESOURCE_FULLNAME", required = true, schema = @Schema(implementation = String.class, example = "test/")) }) @DeleteMapping() @ResponseStatus(HttpStat...
@Test public void testDeleteResource() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); Mockito.when(resourcesService.delete(Mockito.any(), Mockito.anyString(), Mockito.anyString())) .thenReturn(mockResult); ...
public abstract Duration parse(String text);
@Test public void testLongDays() { Assert.assertEquals(Duration.ofDays(1), DurationStyle.LONG.parse("1 days")); Assert.assertEquals(Duration.ofDays(2), DurationStyle.LONG.parse("2 days")); }
@Override public AuthUser getAuthUser(Integer socialType, Integer userType, String code, String state) { // 构建请求 AuthRequest authRequest = buildAuthRequest(socialType, userType); AuthCallback authCallback = AuthCallback.builder().code(code).state(state).build(); // 执行请求 AuthR...
@Test public void testAuthSocialUser_fail() { // 准备参数 Integer socialType = SocialTypeEnum.WECHAT_MP.getType(); Integer userType = randomPojo(UserTypeEnum.class).getValue(); String code = randomString(); String state = randomString(); // mock 方法(AuthRequest) Au...
public static int getUTCTimestamp() { return (int) (System.currentTimeMillis() / 1000); }
@Test public void testGetUTCTimestamp() { assertTrue(Tools.getUTCTimestamp() > 0); }
public static MetricsInfo info(String name, String description) { return Info.INSTANCE.cache.add(name, description); }
@Test public void testInfo() { MetricsInfo info = info("m", "m desc"); assertSame("same info", info, info("m", "m desc")); }
public static <T> T[] replaceFirst(T[] src, T oldValue, T[] newValues) { int index = indexOf(src, oldValue); if (index == -1) { return src; } T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length - 1 + newValues.length); // copy the first p...
@Test public void replace_whenSrcEmpty() { Integer[] result = replaceFirst(new Integer[]{}, 6, new Integer[]{3, 4}); System.out.println(Arrays.toString(result)); assertArrayEquals(new Integer[]{}, result); }
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertInt() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("int4").dataType("int4").build(); Column column = PostgresTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), colu...
@Description("Return the parent for a Bing tile") @ScalarFunction("bing_tile_parent") @SqlType(BingTileType.NAME) public static long bingTileParent(@SqlType(BingTileType.NAME) long input) { BingTile tile = BingTile.decode(input); try { return tile.findParent().encode(); ...
@Test public void testBingTileParent() { assertBingTileParent("03", OptionalInt.empty(), "0"); assertBingTileParent("0123", OptionalInt.of(2), "01"); assertInvalidFunction("bing_tile_parent(bing_tile('0'), 2)", "newZoom must be less than or equal to current zoom 1: 2"); assertInv...
@Override public boolean add(T e) { if (size == Integer.MAX_VALUE) { throw new RuntimeException("Can't add an additional element to the " + "list; list already has INT_MAX elements."); } if (lastChunk == null) { addChunk(initialChunkCapacity); } else if (lastChunk.size() >= lastC...
@Test public void testPerformance() { String obj = "hello world"; final int numElems = 1000000; final int numTrials = 5; for (int trial = 0; trial < numTrials; trial++) { System.gc(); { ArrayList<String> arrayList = new ArrayList<String>(); StopWatch sw = new Stop...
@Override public Connection getConnection() throws SQLException { return dataSourceProxyXA.getConnection(); }
@Test public void testGetMariaXaConnection() throws SQLException, ClassNotFoundException { // Mock Driver driver = Mockito.mock(Driver.class); Class clazz = Class.forName("org.mariadb.jdbc.MariaDbConnection"); Connection connection = (Connection)(Mockito.mock(clazz)); Mockito...
@Nonnull public static String withEmptyFallback(@Nullable String defaultText, @Nonnull String fallback) { if (defaultText == null || defaultText.trim().isBlank()) return fallback; return defaultText; }
@Test void testWithEmptyFallback() { assertEquals("fall", StringUtil.withEmptyFallback(null, "fall")); assertEquals("fall", StringUtil.withEmptyFallback("", "fall")); assertEquals("fall", StringUtil.withEmptyFallback(" ", "fall")); assertEquals("fall", StringUtil.withEmptyFallback("\n", "fall")); assertEqual...
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_mcc() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("mcc310", config); assertThat(config.mcc).isEqualTo(310); }
protected void warn(String warning) { LOG.warn(warning); }
@Test public void testWarnWhenMultiplePatternsMatch() { StrictFieldProjectionFilter filter = createMockBuilder(StrictFieldProjectionFilter.class) .withConstructor(Arrays.asList("a.b.c.{x_average,z_average}", "a.*_average")) .addMockedMethod("warn") .createMock(); // set expectations ...
private void cleanReleaseHistory(ReleaseHistory cleanRelease) { String appId = cleanRelease.getAppId(); String clusterName = cleanRelease.getClusterName(); String namespaceName = cleanRelease.getNamespaceName(); String branchName = cleanRelease.getBranchName(); int retentionLimit = this.getReleaseH...
@Test @Sql(scripts = "/sql/release-history-test.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/clean.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testCleanReleaseHistory() { ReleaseHistoryService service = (ReleaseHistoryService) AopProxyUtils.getSinglet...
@Override public List<ColumnStatistics> getTableColumnStatistics( String catName, String dbName, String tableName, List<String> colNames) throws MetaException, NoSuchObjectException { // Note: this will get stats without verifying ACID. boolean committed = false; Query query = null...
@Test (expected = NoSuchObjectException.class) public void testTableOpsWhenTableDoesNotExist() throws NoSuchObjectException, MetaException { List<String> colNames = Arrays.asList("c0", "c1"); objectStore.getTableColumnStatistics(DEFAULT_CATALOG_NAME, DB1, "not_existed_table", colNames, ENGINE, ""); }
@Override public String toString(final RouteUnit routeUnit) { StringBuilder result = new StringBuilder(); appendInsertValue(routeUnit, result); result.delete(result.length() - 2, result.length()); return result.toString(); }
@Test void assertToStringWithRouteUnit() { assertThat(shardingInsertValuesToken.toString(routeUnit), is("('shardingsphere', 'test')")); }
@Override public Long createRewardActivity(RewardActivityCreateReqVO createReqVO) { // 校验商品是否冲突 validateRewardActivitySpuConflicts(null, createReqVO.getProductSpuIds()); // 插入 RewardActivityDO rewardActivity = RewardActivityConvert.INSTANCE.convert(createReqVO) .setS...
@Test public void testCreateRewardActivity_success() { // 准备参数 RewardActivityCreateReqVO reqVO = randomPojo(RewardActivityCreateReqVO.class, o -> { o.setConditionType(randomEle(PromotionConditionTypeEnum.values()).getType()); o.setProductScope(randomEle(PromotionProductScopeE...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldCastDecimalRoundingDownNegative() { // When: final BigDecimal decimal = DecimalUtil.cast(new BigDecimal("-1.19"), 2, 1); // Then: assertThat(decimal, is(new BigDecimal("-1.2"))); }
@Override public int read() throws IOException { if (mPosition == mLength) { // at end of file return -1; } updateStreamIfNeeded(); int res = mUfsInStream.get().read(); if (res == -1) { return -1; } mPosition++; Metrics.BYTES_READ_FROM_UFS.inc(1); return res; }
@Test public void readAllByteBuffer() throws IOException, AlluxioException { int len = CHUNK_SIZE * 5; int start = 0; AlluxioURI ufsPath = getUfsPath(); createFile(ufsPath, CHUNK_SIZE * 5); ByteBuffer buffer = ByteBuffer.allocate(CHUNK_SIZE); try (FileInStream inStream = getStream(ufsPath)) { ...