focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Properties getConfig(RedisClusterNode node, String pattern) { RedisClient entry = getEntry(node); RFuture<List<String>> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_GET, pattern); List<String> r = syncFuture(f); if (r != null) { ...
@Test public void testGetConfig() { RedisClusterNode master = getFirstMaster(); Properties config = connection.getConfig(master, "*"); assertThat(config.size()).isGreaterThan(20); }
static int encodedBufferSize(int len, boolean breakLines) { // Cast len to long to prevent overflow long len43 = ((long) len << 2) / 3; // Account for padding long ret = (len43 + 3) & ~3; if (breakLines) { ret += len43 / MAX_LINE_LENGTH; } return re...
@Test public void testOverflowEncodedBufferSize() { assertEquals(Integer.MAX_VALUE, Base64.encodedBufferSize(Integer.MAX_VALUE, true)); assertEquals(Integer.MAX_VALUE, Base64.encodedBufferSize(Integer.MAX_VALUE, false)); }
public static boolean isMonomorphic(Class<?> targetType) { if (targetType.isArray()) { return isMonomorphic(targetType.getComponentType()); } // Although enum itself can be non-final, but it's subclass can only be anonymous // inner class, which is final, and we serialize enum by value, which alre...
@Test public void testMonomorphic() { Assert.assertTrue(ReflectionUtils.isMonomorphic(MonomorphicTestEnum1.class)); Assert.assertTrue(ReflectionUtils.isMonomorphic(MonomorphicTestEnum2.class)); Assert.assertTrue(ReflectionUtils.isMonomorphic(MonomorphicTestEnum1[].class)); Assert.assertTrue(Reflection...
public CeQueueDto setTaskType(String s) { checkArgument(s.length() <= 40, "Value of task type is too long: %s", s); this.taskType = s; return this; }
@Test void setTaskType_accepts_empty_and_string_15_chars_or_less() { assertThatNoException().isThrownBy(() -> underTest.setTaskType("")); assertThatNoException().isThrownBy(() -> underTest.setTaskType("bar")); assertThatNoException().isThrownBy(() -> underTest.setTaskType(STR_15_CHARS)); }
public static InetAddress bindToLocalAddress(InetAddress localAddr, boolean bindWildCardAddress) { if (!bindWildCardAddress) { return localAddr; } return null; }
@Test public void testBindToLocalAddress() throws Exception { assertNotNull(NetUtils .bindToLocalAddress(NetUtils.getLocalInetAddress("127.0.0.1"), false)); assertNull(NetUtils .bindToLocalAddress(NetUtils.getLocalInetAddress("127.0.0.1"), true)); }
@Override public void registerInstance(String serviceName, String ip, int port) throws NacosException { registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME); }
@Test void testRegisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); //when client.registerInstance(serviceName, instance); //then verify(proxy, times(1)).registerService(serviceName, Constants...
public String generateComplexTypeColumnTask(long tableId, long dbId, String tableName, String dbName, List<ColumnStats> complexTypeStats) { String sep = ", "; String prefix = "INSERT INTO " + STATISTICS_DB_NAME + "." + SAMPLE_STATISTICS_TABLE_NAME + " VALU...
@Test public void generateComplexTypeColumnTask() { SampleInfo sampleInfo = tabletSampleManager.generateSampleInfo("test", "t_struct"); List<String> columnNames = table.getColumns().stream().map(Column::getName).collect(Collectors.toList()); List<Type> columnTypes = table.getColumns().stream...
public Object format(long timestamp) { return dateTimeFormatter == null ? timestamp : dateTimeFormatter.format(Instant.ofEpochMilli(timestamp)); }
@Test void testDoNotFormatTimestamp() { TimestampFormatter timestampFormatter = new TimestampFormatter(null, ZoneId.of("GMT+01:00")); assertThat(timestampFormatter.format(timestamp)).isEqualTo(timestamp); }
public String getMountedExternalStorageDirectoryPath() { String path = null; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { path = getExternalStorageDirectoryPath(); } return path...
@Test public void getMountedExternalStorageDirectoryPathReturnsNullWhenEjecting() { ShadowEnvironment.setExternalStorageState(Environment.MEDIA_EJECTING); assertThat(contextUtil.getMountedExternalStorageDirectoryPath(), is(nullValue())); }
@Override public RowData nextRecord(RowData reuse) { // return the next row row.setRowId(this.nextRow++); return row; }
@Test void testReadFileWithPartitionValues() throws IOException { FileInputSplit[] splits = createSplits(testFileFlat, 4); long cnt = 0; long totalF0 = 0; // read all splits for (FileInputSplit split : splits) { try (OrcColumnarRowSplitReader reader = ...
public Object execute(GlobalLockExecutor executor) throws Throwable { boolean alreadyInGlobalLock = RootContext.requireGlobalLock(); if (!alreadyInGlobalLock) { RootContext.bindGlobalLockFlag(); } // set my config to config holder so that it can be access in further executio...
@Test void testNested() { assertDoesNotThrow(() -> { template.execute(new GlobalLockExecutor() { @Override public Object execute() { assertTrue(RootContext.requireGlobalLock(), "fail to bind global lock flag"); assertSame(co...
public static byte[] toDerFormat(ECDSASignature signature) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { DERSequenceGenerator seq = new DERSequenceGenerator(baos); seq.addObject(new ASN1Integer(signature.r)); seq.addObject(new ASN1Integer(signature.s)); ...
@Test void toDerFormat() { byte[] signDER = CryptoUtils.toDerFormat(ecdsaSignatureExample); assertArrayEquals(Numeric.hexStringToByteArray(TX_SIGN_FORMAT_DER_HEX), signDER); }
@Override public Iterator<Part> iterator() { return Iterators.unmodifiableIterator(parts.iterator()); }
@Test public void testBasic() { UriSpec spec = new UriSpec("{one}{two}three-four-five{six}seven{eight}"); Iterator<UriSpec.Part> iterator = spec.iterator(); checkPart(iterator.next(), "one", true); checkPart(iterator.next(), "two", true); checkPart(iterator.next(), "three-fou...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CreateOptions)) { return false; } CreateOptions that = (CreateOptions) o; return Objects.equal(mAcl, that.mAcl) && (mCreateParent == that.mCreateParent) && (mEnsureAtomic ...
@Test public void equalsTest() throws Exception { new EqualsTester() .addEqualityGroup( CreateOptions.defaults(mConfiguration), CreateOptions.defaults(mConfiguration)) .testEquals(); }
static <T> T executeCallable(Observation observation, Callable<T> callable) throws Exception { return decorateCallable(observation, callable).call(); }
@Test public void shouldExecuteCallable() throws Throwable { given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world"); String value = Observations .executeCallable(observation, helloWorldService::returnHelloWorldWithException); assertThatObservationWas...
private RemotingCommand receiveReplyMessage(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); long receiveTime = System.currentTimeMillis(); ReplyMessageRequestHeader reques...
@Test public void testReceiveReplyMessage() throws Exception { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); RemotingCommand request = mock(RemotingCommand.class); when(request.getCode()).thenReturn(RequestCode.PUSH_REPLY_MESSAGE_TO_CLIENT); when(request.getBody()).t...
public static final String encryptPassword( String password ) { return encoder.encode( password, false ); }
@Test public void testEncryptPassword() throws KettleValueException { String encryption; encryption = Encr.encryptPassword( null ); assertTrue( "".equals( encryption ) ); encryption = Encr.encryptPassword( "" ); assertTrue( "".equals( encryption ) ); encryption = Encr.encryptPassword( " ...
@Override public DataNodeDto stopNode(String nodeId) throws NodeNotFoundException { final DataNodeDto node = nodeService.byNodeId(nodeId); if (node.getDataNodeStatus() != DataNodeStatus.AVAILABLE) { throw new IllegalArgumentException("Only running data nodes can be stopped."); } ...
@Test public void stopNodePublishesClusterEvent() throws NodeNotFoundException { final String testNodeId = "node"; nodeService.registerServer(buildTestNode(testNodeId, DataNodeStatus.AVAILABLE)); classUnderTest.stopNode(testNodeId); verify(clusterEventBus).post(DataNodeLifecycleEvent...
public static void main(String[] args) { // initialize and wire the system var menuStore = new MenuStore(); Dispatcher.getInstance().registerStore(menuStore); var contentStore = new ContentStore(); Dispatcher.getInstance().registerStore(contentStore); var menuView = new MenuView(); menuStor...
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public Object evaluateReasonCodeValue(final ProcessingDTO processingDTO) { final List<String> orderedReasonCodes = processingDTO.getOrderedReasonCodes(); if (rank != null) { int index = rank - 1; String resultCode = null; if (index < orderedReasonCodes.size()) { ...
@Test void evaluateReasonCodeValue() { KiePMMLOutputField kiePMMLOutputField = KiePMMLOutputField.builder("outputfield", Collections.emptyList()) .withResultFeature(RESULT_FEATURE.REASON_CODE) .withRank(4) .build(); final List<String> reasonCodes = Int...
String generateJwtAssertion() { final long utcPlusWindow = Clock.systemUTC().millis() / 1000 + JWT_CLAIM_WINDOW; final String audience = config.getJwtAudience() != null ? config.getJwtAudience() : config.getLoginUrl(); final StringBuilder claim = new StringBuilder().append("{\"iss\":\"").append...
@Test public void shouldGenerateJwtTokens() { final SalesforceLoginConfig config = new SalesforceLoginConfig("https://login.salesforce.com", "ABCD", "username", parameters, true); final SalesforceSession session = new SalesforceSession(new DefaultCamelContext(), mock...
public ConfigHistoryInfo getConfigHistoryInfo(String dataId, String group, String namespaceId, Long nid) throws AccessException { ConfigHistoryInfo configHistoryInfo = historyConfigInfoPersistService.detailConfigHistory(nid); if (Objects.isNull(configHistoryInfo)) { return null; ...
@Test void testGetConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); configHistoryInfo.setGroup(TEST_GROUP); configHistoryInfo.setContent(TEST_CONTENT); configHistoryInfo.se...
public void setSendFullErrorException(boolean sendFullErrorException) { this.sendFullErrorException = sendFullErrorException; }
@Test void handleFlowableContentNotSupportedExceptionWithoutSendFullErrorException() throws Exception { testController.exceptionSupplier = () -> new FlowableContentNotSupportedException("other test content not supported"); handlerAdvice.setSendFullErrorException(false); String body = mockMv...
public static String toOperationDesc(Operation op) { Class<? extends Operation> operationClass = op.getClass(); if (PartitionIteratingOperation.class.isAssignableFrom(operationClass)) { PartitionIteratingOperation partitionIteratingOperation = (PartitionIteratingOperation) op; Op...
@Test public void testBackupOperation() throws UnknownHostException { Backup backup = new Backup(new DummyBackupOperation(), new Address("127.0.0.1", 5701), new long[]{}, false); String result = toOperationDesc(backup); assertEquals(format("Backup(%s)", DummyBackupOperation.class.getName()),...
public static PostgreSQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find PostgreSQL type '%s' in column type when process binary protocol value", binaryColumnType); return ...
@Test void assertGetInt2BinaryProtocolValue() { PostgreSQLBinaryProtocolValue binaryProtocolValue = PostgreSQLBinaryProtocolValueFactory.getBinaryProtocolValue(PostgreSQLColumnType.INT2); assertThat(binaryProtocolValue, instanceOf(PostgreSQLInt2BinaryProtocolValue.class)); }
public <OutT> void registerInputMessageStreams( PValue pvalue, List<? extends InputDescriptor<KV<?, OpMessage<OutT>>, ?>> inputDescriptors) { registerInputMessageStreams(pvalue, inputDescriptors, this::registerMessageStream); }
@Test public void testRegisterInputMessageStreams() { final PCollection output = mock(PCollection.class); List<String> topics = Arrays.asList("stream1", "stream2"); List inputDescriptors = topics.stream() .map(topicName -> createSamzaInputDescriptor(topicName, topicName)) ....
public static List<Transformation<?>> optimize(List<Transformation<?>> transformations) { final Map<Transformation<?>, Set<Transformation<?>>> outputMap = buildOutputMap(transformations); final LinkedHashSet<Transformation<?>> chainedTransformations = new LinkedHashSet<>(); fina...
@Test void testChainingMultipleOperators() { ExternalPythonKeyedProcessOperator<?> keyedProcessOperator = createKeyedProcessOperator( "f1", new RowTypeInfo(Types.INT(), Types.INT()), Types.STRING()); ExternalPythonProcessOperator<?, ?> processOperator1 = ...
public GetLoanResponse createLoan(CreateLoanRequest createLoanRequest) { String loanId = UUID.randomUUID().toString(); LoanDto loanDto = new LoanDto( loanId, createLoanRequest.term(), createLoanRequest.originatedAmount(), createLoanRequest....
@Test public void testCreateLoan_BNPL() { int term = 4; BigDecimal originatedAmount = BigDecimal.valueOf(100.0); String currency = "USD"; String externalReference = UUID.randomUUID().toString(); LocalDate startDate = LocalDate.of(2023, 1, 1); LocalDate endDate = start...
@Override public void unregister(InetSocketAddress address) { // stop heartbeat if (heartBeatScheduledFuture != null && !heartBeatScheduledFuture.isCancelled()) { heartBeatScheduledFuture.cancel(true); } NetUtil.validAddress(address); Instance instance = Instance...
@Test public void testUnregister() throws Exception { RegistryService registryService = new NamingserverRegistryProvider().provide(); InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088); //1.register registryService.register(inetSocketAddress1); /...
public List<StepMeta> findPreviousSteps( StepMeta stepMeta ) { return findPreviousSteps( stepMeta, true ); }
@Test public void findPreviousStepsNullMeta( ) { TransMeta transMeta = new TransMeta( new Variables() ); List<StepMeta> result = transMeta.findPreviousSteps( null, false ); assertThat( 0, equalTo( result.size() ) ); assertThat( result, equalTo( new ArrayList<>() ) ); }
@Override public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { final Path copy = proxy.copy(source, renamed, status, connectionCallback, new DisabledStreamListener()); ...
@Test public void testMoveWithServerSideEncryptionBucketPolicy() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)); ...
public static byte[] encode(final Object obj) { if (obj == null) { return null; } final String json = toJson(obj, false); return json.getBytes(CHARSET_UTF8); }
@Test public void testEncode() { class Foo extends RemotingSerializable { Map<Long, String> map = new HashMap<>(); Foo() { map.put(0L, "Test"); } public Map<Long, String> getMap() { return map; } } ...
public synchronized void quitElection(boolean needFence) { LOG.info("Yielding from election"); if (!needFence && state == State.ACTIVE) { // If active is gracefully going back to standby mode, remove // our permanent znode so no one fences us. tryDeleteOwnBreadCrumbNode(); } reset(); ...
@Test public void testQuitElection() throws Exception { elector.joinElection(data); Mockito.verify(mockZK, Mockito.times(0)).close(); elector.quitElection(true); Mockito.verify(mockZK, Mockito.times(1)).close(); // no watches added verifyExistCall(0); byte[] data = new byte[8]; electo...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "overridden generic resource interface default methods") public void testTicket3149() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(MainResource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /test:...
@Override public Object intercept(final Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); //Elegant access to object properties through MetaObject, here is access to the properties of statementHandler; //MetaObject is an...
@Test public void interceptTest() { final OracleSQLPrepareInterceptor oracleSQLPrepareInterceptor = new OracleSQLPrepareInterceptor(); final Invocation invocation = mock(Invocation.class); final StatementHandler statementHandler = mock(StatementHandler.class); when(invocation.getTarg...
public static String ofString(final Supplier<String> supplier) { return GsonUtils.getInstance().toJson(initQueryParams(supplier.get())); }
@Test public void testOfString() { assertEquals("{\"a\":\"1\",\"b\":\"2\"}", HttpParamConverter.ofString(() -> "a=1&b=2")); }
public static ColumnWriter createColumnWriter( int nodeIndex, int sequence, List<OrcType> orcTypes, Type type, ColumnWriterOptions columnWriterOptions, OrcEncoding orcEncoding, DateTimeZone hiveStorageTimeZone, DwrfEncryptio...
@Test(dataProvider = "dataForSequenceIdTest") public void testSequenceIdPassedAllColumnWriters(List<OrcType> orcTypes, Type type, Block block) throws IOException { ColumnWriterOptions columnWriterOptions = ColumnWriterOptions.builder() .setCompressionKind(CompressionKind.ZLIB...
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execut...
@Test public void shouldShowHintWhenFailingToCreateQueryIfSelectingFromSourceNameWithMisspelling() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create stream \"Bar\" as select * from test1;", ksqlConfig, ...
@Override protected void handleTcClientConnectRequest(CommandTcClientConnectRequest command) { checkArgument(state == State.Connected); final long requestId = command.getRequestId(); final TransactionCoordinatorID tcId = TransactionCoordinatorID.get(command.getTcId()); if (log.isDebu...
@Test(expectedExceptions = IllegalArgumentException.class) public void shouldFailHandleTcClientConnectRequest() throws Exception { ServerCnx serverCnx = mock(ServerCnx.class, CALLS_REAL_METHODS); Field stateUpdater = ServerCnx.class.getDeclaredField("state"); stateUpdater.setAccessible(true)...
@Override public Service queryService(String serviceName) throws NacosException { return queryService(serviceName, Constants.DEFAULT_GROUP); }
@Test void testQueryService1() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; //when nacosNamingMaintainService.queryService(serviceName, groupName); //then verify(serverProxy, times(1)).queryService(serviceName, ...
@Override public UfsDirectoryStatus copy() { return new UfsDirectoryStatus(this); }
@Test public void copy() { short mode = 077; UfsDirectoryStatus statusToCopy = new UfsDirectoryStatus("name", "owner", "group", mode); UfsDirectoryStatus status = new UfsDirectoryStatus(statusToCopy); assertEquals(statusToCopy, status); }
protected void hideAllAfterModel(EpoxyModel<?> model) { hideModels(getAllModelsAfter(model)); }
@Test public void testHideAllAfterModel() { List<TestModel> models = new ArrayList<>(); int modelCount = 10; for (int i = 0; i < modelCount; i++) { TestModel model = new TestModel(); models.add(model); testAdapter.addModels(model); } int hideIndex = 5; testAdapter.hideAllAft...
public static Boolean judge(final ConditionData conditionData, final String realData) { if (Objects.isNull(conditionData) || StringUtils.isBlank(conditionData.getOperator())) { return false; } PredicateJudge predicateJudge = newInstance(conditionData.getOperator()); if (!(pre...
@Test public void testTimerBeforeJudge() { conditionData.setOperator(OperatorEnum.TIME_BEFORE.getAlias()); //Because the realData can't be empty, so the realDate must fill in the values conditionData.setParamValue(MAX_TIME); assertTrue(PredicateJudgeFactory.judge(conditionData, MAX_T...
public static FileOutputStream createForWrite(File f, int permissions) throws IOException { if (skipSecurity) { return insecureCreateForWrite(f, permissions); } else { return NativeIO.getCreateForWriteFileOutputStream(f, permissions); } }
@Test(timeout = 10000) public void testCreateForWrite() throws IOException { try { SecureIOUtils.createForWrite(testFilePathIs, 0777); fail("Was able to create file at " + testFilePathIs); } catch (SecureIOUtils.AlreadyExistsException aee) { // expected } }
public <T> T parse(String input, Class<T> cls) { return readFlow(input, cls, type(cls)); }
@Test void invalidTask() { ConstraintViolationException exception = assertThrows( ConstraintViolationException.class, () -> this.parse("flows/invalids/invalid-task.yaml") ); assertThat(exception.getConstraintViolations().size(), is(2)); assertThat(exception.g...
@Override public void updateLength(SizedWritable<?> key, SizedWritable<?> value) throws IOException { key.length = keySerializer.getLength(key.v); value.length = valueSerializer.getLength(value.v); return; }
@Test public void testUpdateLength() throws IOException { Mockito.mock(DataOutputStream.class); int kvLength = 0; for (int i = 0; i < inputArraySize; i++) { key.reset(inputArray[i].key); value.reset(inputArray[i].value); serializer.updateLength(key, value); // verify whether the ...
@Override public Ring<T> createRing(Map<T, Integer> pointsMap) { return _ringFactory.createRing(pointsMap); }
@Test(groups = { "small", "back-end" }) public void testRandomChangePoints() throws URISyntaxException { int pointNum = 5; int loopNum = 100; Map<String, Integer> pointsMp = buildPointsMap(pointNum); Map<String, Integer> maxPoints = new HashMap<>(pointNum); Random random = new Random(); ...
static Set<PipelineOptionSpec> getOptionSpecs( Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) { Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface); Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods); ImmutableSe...
@Test public void testBaseClassOptions() { Set<PipelineOptionSpec> props = PipelineOptionsReflector.getOptionSpecs(ExtendsSimpleOptions.class, true); assertThat(props, hasItem(allOf(hasName("foo"), hasClass(SimpleOptions.class)))); assertThat(props, hasItem(allOf(hasName("foo"), hasClass(ExtendsS...
public static String simpleTypeDescription(Type input) { StringBuilder builder = new StringBuilder(); format(builder, input); return builder.toString(); }
@Test public void testTypeFormatterOnClasses() throws Exception { assertEquals("Integer", ReflectHelpers.simpleTypeDescription(Integer.class)); assertEquals("int", ReflectHelpers.simpleTypeDescription(int.class)); assertEquals("Map", ReflectHelpers.simpleTypeDescription(Map.class)); assertEquals(getCl...
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComPingPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_PING, payload, connectionSession), instanceOf(MySQLComPingPacket.class)); }
@Override public void execute(Context context) { long count = 0; try (StreamWriter<ProjectDump.Rule> writer = dumpWriter.newStreamWriter(DumpElement.RULES)) { ProjectDump.Rule.Builder ruleBuilder = ProjectDump.Rule.newBuilder(); for (Rule rule : ruleRepository.getAll()) { ProjectDump.Rule ...
@Test public void execute_writes_all_rules_in_order_returned_by_repository() { String[] keys = new String[10]; for (int i = 0; i < 10; i++) { String key = "key_" + i; ruleRepository.add(key); keys[i] = key; } underTest.execute(new TestComputationStepContext()); List<ProjectDump...
@Override public void validatePostList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return; } // 获得岗位信息 List<PostDO> posts = postMapper.selectBatchIds(ids); Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId); // 校验 ids.forEach(id ...
@Test public void testValidatePostList_notFound() { // 准备参数 List<Long> ids = singletonList(randomLongId()); // 调用, 并断言异常 assertServiceException(() -> postService.validatePostList(ids), POST_NOT_FOUND); }
@VisibleForTesting public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics) { if (rowCount == 0) { return Domain.none(type); } if (columnStatistics == null) { return Domain.all(type); } if (columnStatistics.hasN...
@Test public void testDouble() { assertEquals(getDomain(DOUBLE, 0, null), Domain.none(DOUBLE)); assertEquals(getDomain(DOUBLE, 10, null), Domain.all(DOUBLE)); assertEquals(getDomain(DOUBLE, 0, doubleColumnStats(null, null, null)), Domain.none(DOUBLE)); assertEquals(getDomain(DOU...
@ScalarOperator(ADD) @SqlType(StandardTypes.TINYINT) public static long add(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right) { try { return SignedBytes.checkedCast(left + right); } catch (IllegalArgumentException e) { thro...
@Test public void testAdd() { assertFunction("TINYINT'37' + TINYINT'37'", TINYINT, (byte) (37 + 37)); assertFunction("TINYINT'37' + TINYINT'17'", TINYINT, (byte) (37 + 17)); assertFunction("TINYINT'17' + TINYINT'37'", TINYINT, (byte) (17 + 37)); assertFunction("TINYINT'17' + TINY...
public void writeUbyte(int value) throws IOException { if (value < 0 || value > 0xFF) { throw new ExceptionWithContext("Unsigned byte value out of range: %d", value); } write(value); }
@Test(expected=ExceptionWithContext.class) public void testWriteUbyteOutOfBounds() throws IOException { writer.writeUbyte(-1); }
public int getInteger(HazelcastProperty property) { return Integer.parseInt(getString(property)); }
@Test public void testGet_whenFunctionAvailable_andNoOtherSettings() { Properties props = new Properties(); HazelcastProperty p = new HazelcastProperty("key", (Function<HazelcastProperties, Integer>) properties -> 23); HazelcastProperties properties = new HazelcastProperties(props); ...
@ConstantFunction(name = "years_sub", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true) public static ConstantOperator yearsSub(ConstantOperator date, ConstantOperator year) { return ConstantOperator.createDatetimeOrNull(date.getDatetime().minusYears(year.getInt())); }
@Test public void yearsSub() { assertEquals("2005-03-23T09:23:55", ScalarOperatorFunctions.yearsSub(O_DT_20150323_092355, O_INT_10).getDatetime().toString()); }
@Override public CompletionStage<V> putAsync(K key, V value) { return map.putAsync(key, value); }
@Test(expected = MethodNotAvailableException.class) public void testPutAsyncWithExpiryPolicy() { ExpiryPolicy expiryPolicy = new HazelcastExpiryPolicy(1, 1, 1, TimeUnit.MILLISECONDS); adapter.putAsync(42, "value", expiryPolicy); }
public static long encodeShortScaledValue(BigDecimal value, int scale) { checkArgument(scale >= 0); return value.setScale(scale, UNNECESSARY).unscaledValue().longValueExact(); }
@Test public void testEncodeShortScaledValue() { assertEquals(encodeShortScaledValue(new BigDecimal("2.00"), 2), 200L); assertEquals(encodeShortScaledValue(new BigDecimal("2.13"), 2), 213L); assertEquals(encodeShortScaledValue(new BigDecimal("172.60"), 2), 17260L); assertEquals(e...
public String buildFilename() { boolean forceSameOutputFile = "Y".equalsIgnoreCase( System.getProperty( Const.KETTLE_JSON_OUTPUT_FORCE_SAME_OUTPUT_FILE, "N" ) ); if ( forceSameOutputFile ) { return meta.buildFilename( environmentSubstitute( meta.getFileName() ), startProcessingDate ); } r...
@Test public void testBuildFilenameWithoutForceSameOutputFile() { StepMeta stepMeta = mock( StepMeta.class ); JsonOutputData jsonOutputData = mock( JsonOutputData.class ); JsonOutputMeta jsonOutputMeta = mock( JsonOutputMeta.class ); int copyNr = 1; TransMeta transMeta = mock( TransMeta.class ); ...
@Override public Time getTime(final int columnIndex) throws SQLException { return (Time) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Time.class), Time.class); }
@Test void assertGetTimeAndCalendarWithColumnLabel() throws SQLException { Calendar calendar = Calendar.getInstance(); when(mergeResultSet.getCalendarValue(1, Time.class, calendar)).thenReturn(new Time(0L)); assertThat(shardingSphereResultSet.getTime("label", calendar), is(new Time(0L))); ...
@Override public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) { Map<String, List<TopicPartition>> assignment = new HashMap<>(); List<MemberInfo> memberInfoList = new Arra...
@Test public void testMultipleConsumersMixedTopics() { String topic1 = "topic1"; String topic2 = "topic2"; String consumer1 = "consumer1"; String consumer2 = "consumer2"; String consumer3 = "consumer3"; Map<String, Integer> partitionsPerTopic = setupPartitionsPerTopi...
public TaskRunScheduler getTaskRunScheduler() { return taskRunScheduler; }
@Test public void testTaskRunMergeRedundant1() { TaskRunManager taskRunManager = new TaskRunManager(); Task task = new Task("test"); task.setDefinition("select 1"); long taskId = 1; TaskRun taskRun1 = makeTaskRun(taskId, task, makeExecuteOption(true, false)); TaskRun...
@Override public GetLabelsToNodesResponse getLabelsToNodes( GetLabelsToNodesRequest request) throws YarnException, IOException { if (request == null) { routerMetrics.incrLabelsToNodesFailedRetrieved(); String msg = "Missing getNodesToLabels request."; RouterAuditLogger.logFailure(user.getS...
@Test public void testGetLabelsToNodesRequest() throws Exception { LOG.info("Test FederationClientInterceptor : Get Labels To Node request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing getLabelsToNodes request.", () -> interceptor.getLabelsToNodes(null)); // norm...
@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 controlRequestStartRecording2() { internalEncodeLogHeader(buffer, 0, 32, 64, () -> 5_600_000_000L); final StartRecordingRequest2Encoder requestEncoder = new StartRecordingRequest2Encoder(); requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) ...
public static boolean deleteQuietly(@Nullable File file) { if (file == null) { return false; } return deleteQuietly(file.toPath()); }
@Test public void deleteQuietly_deletes_directory_and_content() throws IOException { Path target = temporaryFolder.newFolder().toPath(); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createFil...
public synchronized Schema create(URI id, String refFragmentPathDelimiters) { URI normalizedId = id.normalize(); if (!schemas.containsKey(normalizedId)) { URI baseId = removeFragment(id).normalize(); if (!schemas.containsKey(baseId)) { logger.debug("Reading sch...
@Test public void createWithFragmentResolution() throws URISyntaxException { URI addressSchemaUri = getClass().getResource("/schema/address.json").toURI(); SchemaStore schemaStore = new SchemaStore(); Schema addressSchema = schemaStore.create(addressSchemaUri, "#/."); Schema innerS...
protected T removeMin() { if (tail == null) { return null; } size--; count -= tail.count; T minElement = tail.element; tail = tail.prev; if (tail != null) { tail.next = null; } sampleMap.remove(minElement); return mi...
@Test public void testRemoveMin() { // Empty set assertNull(set.removeMin()); assertEquals(0, set.size()); assertEquals(0L, set.count()); // Maintaining order set.put(e[0]); for (int i = 0; i < 2; i++) { set.put(e[1]); } f...
public void setCve(List<String> cve) { this.cve = cve; }
@Test @SuppressWarnings("squid:S2699") public void testSetCve() { //already tested, this is just left so the IDE doesn't recreate it. }
@Override public ResultSet getTables(Connection connection, String dbName) throws SQLException { return connection.getMetaData().getTables(connection.getCatalog(), dbName, null, new String[] {"TABLE", "VIEW", "MATERIALIZED VIEW", "FOREIGN TABLE"}); }
@Test public void testListTableNames() throws SQLException { new Expectations() { { dataSource.getConnection(); result = connection; minTimes = 0; connection.getCatalog(); result = "t1"; minTimes = 0...
public static Serializer getSerializer(String type) { return SERIALIZER_MAP.get(type.toLowerCase()); }
@Test void testGetSerializer() { Serializer serializer = SerializeFactory.getSerializer("JSON"); assertTrue(serializer instanceof JacksonSerializer); }
long loadFSEdits(EditLogInputStream edits, long expectedStartingTxId) throws IOException { return loadFSEdits(edits, expectedStartingTxId, Long.MAX_VALUE, null, null); }
@Test public void testLoadFSEditLogThrottling() throws Exception { FSNamesystem namesystem = mock(FSNamesystem.class); namesystem.dir = mock(FSDirectory.class); FakeTimer timer = new FakeTimer(); FSEditLogLoader loader = new FSEditLogLoader(namesystem, 0, timer); FSEditLogLoader.LOAD_EDITS_LOG_HE...
@Override public ListenableFuture<HttpResponse> sendAsync(HttpRequest httpRequest) { return sendAsync(httpRequest, null); }
@Test public void sendAsync_whenRequestFailed_returnsFutureWithException() { ListenableFuture<HttpResponse> responseFuture = httpClient.sendAsync(get("http://unknownhost/path").withEmptyHeaders().build()); ExecutionException ex = assertThrows(ExecutionException.class, responseFuture::get); assert...
public static boolean notMarkedWithNoAutoStart(Object o) { if (o == null) { return false; } Class<?> clazz = o.getClass(); NoAutoStart a = findAnnotation(clazz, NoAutoStart.class); return a == null; }
@Test public void commonObject() { Object o = new Object(); assertTrue(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); }
public void encodeAndOwn(byte[] value, OutputStream outStream, Context context) throws IOException, CoderException { if (!context.isWholeStream) { VarInt.encode(value.length, outStream); outStream.write(value); } else { if (outStream instanceof ExposedByteArrayOutputStream) { ((E...
@Test public void testEncodeAndOwn() throws Exception { for (byte[] value : TEST_VALUES) { byte[] encodedSlow = CoderUtils.encodeToByteArray(TEST_CODER, value); byte[] encodedFast = encodeToByteArrayAndOwn(TEST_CODER, value); assertThat(encodedSlow, equalTo(encodedFast)); } }
@Override public boolean hasMagicHeader() { switch (super.getVersion()) { case DEFAULT_VERSION: return true; default: return true; } }
@Test public void testHasMagicHeader() { assertTrue(verDefault.hasMagicHeader()); assertTrue(verCurrent.hasMagicHeader()); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback connectionCallback) throws BackgroundException { final MantaHttpHeaders headers = new MantaHttpHeaders(); try { try { if(status.isAppend()) { final...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final TransferStatus status = new TransferStatus(); try { final Path drive = new MantaDirectoryFeature(session).mkdir(randomDirectory(), new TransferStatus()); new MantaReadFeature(ses...
@Override public Object collect() { return value; }
@Test public void test_default() { MinSqlAggregation aggregation = new MinSqlAggregation(); assertThat(aggregation.collect()).isNull(); }
@Override public ReservationListResponse listReservations( ReservationListRequest requestInfo) throws YarnException, IOException { // Check if reservation system is enabled checkReservationSystem(); ReservationListResponse response = recordFactory.newRecordInstance(ReservationListRespo...
@Test public void testListReservationsByReservationId() { resourceManager = setupResourceManager(); ClientRMService clientService = resourceManager.getClientRMService(); Clock clock = new UTCClock(); long arrival = clock.getTime(); long duration = 60000; long deadline = (long) (arrival + 1.05 ...
public Map<String, Object> statusStorageTopicSettings() { return topicSettings(STATUS_STORAGE_PREFIX); }
@Test public void shouldAllowSettingStatusTopicSettings() { Map<String, String> topicSettings = new HashMap<>(); topicSettings.put("foo", "foo value"); topicSettings.put("bar", "bar value"); topicSettings.put("baz.bim", "100"); Map<String, String> settings = configs(); ...
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 givenFloatWithSurroundingSpaces_parses() { Float floatNum = Float.parseFloat("3.141592"); DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" 3.141592 ", floatNum); Schema schema = Schema.builder() .addFloatField("a_float") .addInt32Field("an_i...
public B module(ModuleConfig module) { this.module = module; return getThis(); }
@Test void module() { ModuleConfig moduleConfig = new ModuleConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.module(moduleConfig); Assertions.assertEquals(moduleConfig, builder.build().getModule()); }
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { SQLStatement dalStatement = sqlStatementContext.getSq...
@Test void assertMergeForShowOtherStatement() throws SQLException { DALStatement dalStatement = new MySQLShowOtherStatement(); SQLStatementContext sqlStatementContext = mockSQLStatementContext(dalStatement); ShardingDALResultMerger resultMerger = new ShardingDALResultMerger(DefaultDatabase.L...
public static void localRunnerNotification(JobConf conf, JobStatus status) { JobEndStatusInfo notification = createNotification(conf, status); if (notification != null) { do { try { int code = httpNotification(notification.getUri(), notification.getTimeout()); if ...
@Test public void testLocalJobRunnerUriSubstitution() throws InterruptedException { JobStatus jobStatus = createTestJobStatus( "job_20130313155005308_0001", JobStatus.SUCCEEDED); JobConf jobConf = createTestJobConf( new Configuration(), 0, baseUrl + "jobend?jobid=$jobId&status=$jobStat...
@Override public void updateSensitiveWord(SensitiveWordSaveVO updateReqVO) { // 校验唯一性 validateSensitiveWordExists(updateReqVO.getId()); validateSensitiveWordNameUnique(updateReqVO.getId(), updateReqVO.getName()); // 更新 SensitiveWordDO updateObj = BeanUtils.toBean(updateReqVO...
@Test public void testUpdateSensitiveWord_notExists() { // 准备参数 SensitiveWordSaveVO reqVO = randomPojo(SensitiveWordSaveVO.class); // 调用, 并断言异常 assertServiceException(() -> sensitiveWordService.updateSensitiveWord(reqVO), SENSITIVE_WORD_NOT_EXISTS); }
@Override public String getSessionId() { return sessionID; }
@Test public void testEditConfigRequestWithChunkedFraming() { log.info("Starting edit-config async"); assertNotNull("Incorrect sessionId", session3.getSessionId()); try { assertTrue("NETCONF edit-config command failed", session3.editConfig(RUNNING, ...
@Override public int hashCode() { return sql.hashCode(); }
@Test public void testHashCode() { SqlPredicate sql = new SqlPredicate("foo='bar'"); assertEquals("foo='bar'".hashCode(), sql.hashCode()); }
@Override public long getAndDecrement(K key) { return complete(asyncCounterMap.getAndDecrement(key)); }
@Test public void testGetAndDecrement() { atomicCounterMap.put(KEY1, VALUE1); Long beforeDecrement = atomicCounterMap.getAndDecrement(KEY1); assertThat(beforeDecrement, is(VALUE1)); Long afterDecrement = atomicCounterMap.get(KEY1); assertThat(afterDecrement, is(VALUE1 - 1)); ...
void generateDecodeCodeForAMessage(Map<String, MessageDecoderMethod> msgDecodeCode, Queue<Descriptors.Descriptor> queue, Set<String> fieldsToRead) { Descriptors.Descriptor descriptor = queue.remove(); String fullyQualifiedMsgName = ProtoBufUtils.getFullJavaName(descriptor); int varNum = 1; if (msg...
@Test public void testGenerateDecodeCodeForAMessageForOnlySomeFieldsToRead() throws URISyntaxException, IOException { MessageCodeGen messageCodeGen = new MessageCodeGen(); Queue<Descriptors.Descriptor> queue = new ArrayDeque<>(); Map<String, MessageCodeGen.MessageDecoderMethod> msgDe...
@VisibleForTesting DictTypeDO validateDictTypeExists(Long id) { if (id == null) { return null; } DictTypeDO dictType = dictTypeMapper.selectById(id); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); } return dictType; }
@Test public void testValidateDictDataExists_success() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 调用成功 dictTypeService.validateDictTypeExists(dbDictType.getId()); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromSnapshotId() throws Exception { appendTwoSnapshots(); ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_ID) .startSnapshotId(snapshot2.snapshotId()) .build(); ...
@Override public long length() throws IOException { checkClosed(); return size; }
@Test void testPathConstructor() throws IOException, URISyntaxException { try (RandomAccessRead randomAccessSource = new RandomAccessReadMemoryMappedFile( Paths.get(getClass().getResource("RandomAccessReadFile1.txt").toURI()))) { assertEquals(130, randomAccessSource.l...
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType); return BINARY_PRO...
@Test void assertGetBinaryProtocolValueWithMySQLTypeTiny() { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.TINY), instanceOf(MySQLInt1BinaryProtocolValue.class)); }
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(containerService.isContainer(folder)) { final B2BucketResponse response = session.getClient().createBucket(containerService.getContainer(folder).getName(), ...
@Test public void testCreateBucket() throws Exception { final Path bucket = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)); final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final B2DirectoryFeature feature = new...
@VisibleForTesting Object evaluate(final GenericRow row) { return term.getValue(new TermEvaluationContext(row)); }
@Test public void shouldEvaluateStruct() { // Given: final Expression expression1 = new CreateStructExpression( ImmutableList.of( new Field("A", new IntegerLiteral(10)), new Field("B", new StringLiteral("abc")) ) ); // When: InterpretedExpression interpret...
public void completeTx(SendRequest req) throws InsufficientMoneyException, CompletionException { lock.lock(); try { checkArgument(!req.completed, () -> "given SendRequest has already been completed"); log.info("Completing send tx with {} outputs totalling {} ...
@Test(expected = Wallet.DustySendRequested.class) public void sendDustAndOpReturnWithoutValueTest() throws Exception { // Tests sending dust and OP_RETURN without value, should throw DustySendRequested because sending sending dust is not allowed in any case. receiveATransactionAmount(wallet, myAddre...
@Override public String toString() { return this.getClass().getSimpleName() + " " + type.getName() + " r:" + repetitionLevel + " d:" + definitionLevel + " " + Arrays.toString(fieldPath); }
@Test public void testSchema() { assertEquals(schemaString, schema.toString()); }
@NonNull @Override public FileObject getResolvedFileObject() { return resolvedFileObject; }
@Test public void testGetResolvedFileObject() { assertEquals( resolvedFileObject, fileObject.getResolvedFileObject() ); }
@Override public void onServerStart(Server server) { if (!done) { initCe(); this.done = true; } }
@Test public void clean_queue_then_start_scheduler_of_workers() { underTest.onServerStart(server); verify(processingScheduler).startScheduling(); verify(cleaningScheduler).startScheduling(); }
@Override public Schema getTargetSchema() { String registryUrl = getStringWithAltKeys(config, HoodieSchemaProviderConfig.SRC_SCHEMA_REGISTRY_URL); String targetRegistryUrl = getStringWithAltKeys(config, HoodieSchemaProviderConfig.TARGET_SCHEMA_REGISTRY_URL, registryUrl); try { return parseSc...
@Test public void testGetTargetSchemaShouldRequestSchemaWithoutCreds() throws Exception { TypedProperties props = getProps(); props.put("hoodie.deltastreamer.schemaprovider.registry.url", "http://localhost/subjects/test/versions/latest"); SchemaRegistryProvider underTest = getUnderTest(props, -1, true); ...