focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void initialize(URI uri, Configuration conf) throws IOException { requireNonNull(uri, "uri is null"); requireNonNull(conf, "conf is null"); super.initialize(uri, conf); setConf(conf); this.uri = URI.create(uri.getScheme() + "://" + uri.getAut...
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Error creating an instance of .*") public void testCustomCredentialsClassCannotBeFound() throws Exception { Configuration config = new Configuration(); config.set(S3_USE_INSTANCE_CREDENTIALS, "false...
@SuppressWarnings("unchecked") public static int compare(Comparable lhs, Comparable rhs) { assert lhs != null; assert rhs != null; if (lhs.getClass() == rhs.getClass()) { return lhs.compareTo(rhs); } if (lhs instanceof Number && rhs instanceof Number) { ...
@SuppressWarnings("ConstantConditions") @Test(expected = Throwable.class) public void testNullRhsInCompareThrows() { compare(1, null); }
@Override public Integer revRank(V o) { return get(revRankAsync(o)); }
@Test public void testRevRank() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple"); set.add(0.1, "a"); set.add(0.2, "b"); set.add(0.3, "c"); set.add(0.4, "d"); set.add(0.5, "e"); set.add(0.6, "f"); set.add(0.7, "g"); assert...
public static void checkInstanceIsLegal(Instance instance) throws NacosException { if (null == instance) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR, "Instance can not be null."); } if (instance.getInstanceHeartBeatTimeOut(...
@Test void testCheckInstanceIsNull() throws NacosException { Instance instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(9089); NamingUtils.checkInstanceIsLegal(instance); try { NamingUtils.checkInstanceIsLegal(null); } catch (NacosEx...
public static String createGPX(InstructionList instructions, String trackName, long startTimeMillis, boolean includeElevation, boolean withRoute, boolean withTrack, boolean withWayPoints, String version, Translation tr) { DateFormat formatter = Helper.createFormatter(); DecimalFormat decimalFormat = ne...
@Test public void testCreateGPXCorrectFormattingSmallNumbers() { InstructionList instructions = new InstructionList(trMap.getWithFallBack(Locale.US)); PointList pl = new PointList(); pl.add(0.000001, 0.000001); pl.add(-0.000123, -0.000125); Instruction instruction = new Inst...
@Override public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) throws AccessDeniedException { if(input.getOptionValues(action.name()).length == 2) { final String path = input.getOptionValues(action.name())[1]; // This only applies to ...
@Test public void testFind() throws Exception { File.createTempFile("temp", ".duck"); final File f = File.createTempFile("temp", ".duck"); File.createTempFile("temp", ".false"); final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(Termin...
public int registerUser(final User user) throws SQLException { var sql = "insert into USERS (username, password) values (?,?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql) ) { preparedStatement.setString(1, user.g...
@Test void registerShouldSucceed() throws SQLException { var dataSource = createDataSource(); var userTableModule = new UserTableModule(dataSource); var user = new User(1, "123456", "123456"); assertEquals(1, userTableModule.registerUser(user)); }
public Configuration getConfiguration() { return configuration; }
@Test public void getConfiguration() { Configuration configuration = namesrvController.getConfiguration(); Assert.assertNotNull(configuration); }
@Udf public int instr(final String str, final String substring) { return instr(str, substring, 1); }
@Test public void shouldReturnZeroOnNullValue() { assertThat(udf.instr(null, "OR"), is(0)); assertThat(udf.instr(null, "OR", 1), is(0)); assertThat(udf.instr(null, "OR", 1, 1), is(0)); assertThat(udf.instr("CORPORATE FLOOR", null, 1), is(0)); assertThat(udf.instr("CORPORATE FLOOR", null, 1, 1), is...
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testUpdateFetchPositionOfPausedPartitionsWithoutAValidPosition() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0); subscriptions.pause(tp0); // paused partition does not have a valid position offsetFetcher.resetPositio...
RegistryEndpointProvider<Optional<URL>> initializer() { return new Initializer(); }
@Test public void testGetAccept() { Assert.assertEquals(0, testBlobPusher.initializer().getAccept().size()); }
@Override public void finish() throws IOException { if (rowCount == 0) { writer.append("(no rows)\n"); } writer.flush(); }
@Test public void testVerticalPrintingNoRows() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("none"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.finish(); assertEqu...
@Override protected void write(final PostgreSQLPacketPayload payload) { payload.getByteBuf().writeBytes(PREFIX); payload.getByteBuf().writeByte(status); }
@Test void assertReadWriteWithTransactionFailed() { ByteBuf byteBuf = ByteBufTestUtils.createByteBuf(6); PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8); PostgreSQLReadyForQueryPacket packet = PostgreSQLReadyForQueryPacket.TRANSACTION_FAILED; ...
public static String repeat(final String str, final int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } if (repeat <= 0) { return EMPTY; } final int inputLength = str.length(); if (repeat == 1 || inputLeng...
@Test void testRepetition() { assertThat(EncodingUtils.repeat("we", 3)).isEqualTo("wewewe"); }
public static String getGetterMethodName(String property, FullyQualifiedJavaType fullyQualifiedJavaType) { StringBuilder sb = new StringBuilder(); sb.append(property); if (Character.isLowerCase(sb.charAt(0)) && (sb.length() == 1 || !Character.isUpperCase(sb.charAt(1)...
@Test void testGetGetterMethodName() { assertEquals("geteMail", getGetterMethodName("eMail", FullyQualifiedJavaType.getStringInstance())); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("getFirstName", getGetterMethodName("firstName", FullyQualifiedJavaType.getStringInstance())); //$NON-NLS-1$ //$NON-NLS-...
public static <V> List<V> listOrEmpty(List<V> list) { return list == null ? ImmutableList.<V>of() : list; }
@Test public void testNullSafeList() { assertEquals(Collections.emptyList(), Apiary.listOrEmpty(null)); List<?> values = Arrays.asList("abc"); assertSame(values, Apiary.listOrEmpty(values)); }
@Override public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) { Objects.requireNonNull(windows, "windows can't be null"); return new TimeWindowedCogroupedKStreamImpl<>( windows, builder, subTopologySourceNodes, ...
@Test public void shouldNotHaveNullWindowOnWindowedBySliding() { assertThrows(NullPointerException.class, () -> cogroupedStream.windowedBy((SlidingWindows) null)); }
@Override public CompletableFuture<Void> putStateAsync(String key, ByteBuffer value) { ensureStateEnabled(); return defaultStateStore.putAsync(key, value); }
@Test public void testPutStateStateEnabled() throws Exception { context.defaultStateStore = mock(BKStateStoreImpl.class); ByteBuffer buffer = ByteBuffer.wrap("test-value".getBytes(UTF_8)); context.putStateAsync("test-key", buffer); verify(context.defaultStateStore, times(1)).putAsync...
public String generateUniqueProjectKey(String projectName, String... extraProjectKeyItems) { String sqProjectKey = generateCompleteProjectKey(projectName, extraProjectKeyItems); sqProjectKey = truncateProjectKeyIfNecessary(sqProjectKey); return sanitizeProjectKey(sqProjectKey); }
@Test public void generateUniqueProjectKey_shortProjectName_shouldAppendUuid() { String fullProjectName = RandomStringUtils.randomAlphanumeric(10); assertThat(projectKeyGenerator.generateUniqueProjectKey(fullProjectName)) .isEqualTo(generateExpectedKeyName(fullProjectName)); }
public static Exception lookupExceptionInCause(Throwable source, Class<? extends Exception>... clazzes) { while (source != null) { for (Class<? extends Exception> clazz : clazzes) { if (clazz.isAssignableFrom(source.getClass())) { return (Exception) source; ...
@Test void givenNoCause_whenLookupExceptionInCause_thenReturnNull() { assertThat(ExceptionUtil.lookupExceptionInCause(new Exception(), RuntimeException.class)).isNull(); }
@Override public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return join(otherStream, toValueJoinerWithKey(joiner), w...
@Test public void shouldNotAllowNullTableOnTableJoinWithJoiner() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join(null, MockValueJoiner.TOSTRING_JOINER, Joined.as("name"))); assertThat(exception.getMessage(), equalTo("ta...
@Override public List<ApolloAuditLogDTO> queryLogs(int page, int size) { return ApolloAuditUtil.logListToDTOList(logService.findAll(page, size)); }
@Test public void testQueryLogs() { { List<ApolloAuditLog> logList = MockBeanFactory.mockAuditLogListByLength(size); Mockito.when(logService.findAll(Mockito.eq(page), Mockito.eq(size))) .thenReturn(logList); } List<ApolloAuditLogDTO> dtoList = api.queryLogs(page, size); Mockito....
@Override public Object decode(Channel channel, InputStream input) throws IOException { if (log.isDebugEnabled()) { Thread thread = Thread.currentThread(); log.debug("Decoding in thread -- [" + thread.getName() + "#" + thread.getId() + "]"); } int contentLength = inp...
@Test void test() throws Exception { // Mock a rpcInvocation, this rpcInvocation is usually generated by the client request, and stored in // Request#data Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); URL url = new ServiceConfi...
public static List<CredentialRetriever> getFromCredentialRetrievers( CommonCliOptions commonCliOptions, DefaultCredentialRetrievers defaultCredentialRetrievers) throws FileNotFoundException { // these are all mutually exclusive as enforced by the CLI commonCliOptions .getUsernamePassword() ...
@Test @Parameters(method = "paramsFromCredHelper") public void testGetFromCredentialHelper(String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); Credentials.getFromCredentialRetrie...
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 testConvertTypeCaseDecimalLessThanOrEqualMaxDecimal64Precision() { DecimalTypeInfo decimalTypeInfo = TypeInfoFactory.getDecimalTypeInfo(12, 4); Type result = EntityConvertUtils.convertType(decimalTypeInfo); Type expectedType = ScalarType.createDecimalV3Type(PrimitiveType.DE...
public static StringBuilder print_json_diff(LogBuffer buffer, long len, String columnName, int columnIndex, String charsetName) { return print_json_diff(buffer, len, columnName, columnIndex, Charset.forName(charsetName)); }
@Test public void print_json_diffInputNotNullZeroNotNullZeroNotNullOutputIllegalArgumentException() throws InvocationTargetException { // Arrange final LogBuffer buffer = new LogBuffer(); buffer...
public static String substVars(String val, PropertyContainer pc1) throws ScanException { return substVars(val, pc1, null); }
@Test public void testLiteral() throws ScanException { String noSubst = "hello world"; String result = OptionHelper.substVars(noSubst, context); assertEquals(noSubst, result); }
public static List<Integer> reverseSequence(int start, int end, int step) { return sequence(end - 1, start - 1, -step); }
@Test public void reverseSequence() { List<Integer> lst = Iterators.reverseSequence(1, 4); assertEquals(3, (int) lst.get(0)); assertEquals(2, (int) lst.get(1)); assertEquals(1, (int) lst.get(2)); assertEquals(3, lst.size()); }
@VisibleForTesting void validateExperienceOutRange(List<MemberLevelDO> list, Long id, Integer level, Integer experience) { for (MemberLevelDO levelDO : list) { if (levelDO.getId().equals(id)) { continue; } if (levelDO.getLevel() < level) { ...
@Test public void testCreateLevel_experienceOutRange() { // 准备参数 int level = 10; int experience = 10; String name = randomString(); // mock 数据 memberlevelMapper.insert(randomLevelDO(o -> { o.setLevel(level); o.setExperience(experience); ...
public synchronized void start() throws NacosException { if (isStarted || isFixed) { return; } GetServerListTask getServersTask = new GetServerListTask(addressServerUrl); for (int i = 0; i < initServerListRetryTimes && serverUrls.isEmpty(); ++i) { ...
@Test void testStart() throws NacosException { final ServerListManager mgr = new ServerListManager("localhost", 0); try { mgr.start(); fail(); } catch (NacosException e) { assertEquals( "fail to get NACOS-server serverlist! env:custom-l...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, PhotosContainerResource resource) throws Exception { KoofrClient koofrClient = koofrClientFactory.create(authData); monitor.debug( () ->...
@Test public void testImportItemFromJobStoreUserTimeZone() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); when(jobStore.getStream(any(), any())).thenReturn(new InputStreamWrapper(inputStream, 5L)); UUID jobId = UUID.randomUUID(); Portabili...
public void setName(String name) throws IllegalStateException { if (name != null && name.equals(this.name)) { return; // idempotent naming } if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { this.name = name; } else { thr...
@Test public void renameTest() { context.setName("hello"); try { context.setName("x"); Assertions.fail("renaming is not allowed"); } catch (IllegalStateException ise) { } }
public static Object replace(Object root, DataIterator it, Object value) { return transform(root, it, Transforms.constantValue(value)); }
@Test public void testReplaceByPredicate() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPathSpec(IteratorTestData.PATH_TO_ID)) .replace(100); assertEquals(data.g...
@Override public Map<String, String> generationCodes(Long tableId) { // 校验是否已经存在 CodegenTableDO table = codegenTableMapper.selectById(tableId); if (table == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } List<CodegenColumnDO> columns = codegenColumnMapper.se...
@Test public void testGenerationCodes_sub_columnNotExists() { // mock 数据(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene()) .setTemplateType(CodegenTemplateTypeEnum.MASTER_NORMAL.getType()...
@SuppressFBWarnings("NS_NON_SHORT_CIRCUIT") protected boolean isValidUtf8(final byte[] input) { int i = 0; // Check for BOM if (input.length >= 3 && (input[0] & 0xFF) == 0xEF && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) { i = 3; } int...
@Test public void isValidUtf8_testNaughtyStrings_allShouldFail() { MockResponseWriter rw = new MockResponseWriter(); for (int[] s : NAUGHTY_STRINGS) { byte[] buf = new byte[s.length * 4]; int pos = 0; for (int v : s) { for (byte b : convert2Bytes(v...
@Override public R apply(R record) { final Long timestamp = record.timestamp(); if (timestamp == null) { throw new DataException("Timestamp missing on record: " + record); } final String formattedTimestamp = timestampFormat.get().format(new Date(timestamp)); fina...
@Test public void defaultConfiguration() { final SourceRecord record = new SourceRecord( null, null, "test", 0, null, null, null, null, 1483425001864L ); assertEquals("test-20170103", xform.apply(record).topic())...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> children = new AttributedList<>(); ListFolderResult result; this.parse(directory, listener, children, result...
@Test public void testListHome() throws Exception { final AttributedList<Path> list = new DropboxListService(session).list(new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)), new DisabledListProgressListener()); assertNotSame(AttributedList.emptyList(), list); for(Path f : list...
@Override public void failover(NamedNode master) { connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName()); }
@Test public void testFailover() throws InterruptedException { Collection<RedisServer> masters = connection.masters(); connection.failover(masters.iterator().next()); Thread.sleep(10000); RedisServer newMaster = connection.masters().iterator().next(); assert...
@Override public void doPush(String clientId, Subscriber subscriber, PushDataWrapper data) { getPushExecuteService(clientId, subscriber).doPush(clientId, subscriber, data); }
@Test void testDoPushForUdp() { delegate.doPush(udpClientId, subscriber, pushdata); verify(pushExecutorUdp).doPush(udpClientId, subscriber, pushdata); }
public static double parseDouble(final String str) { final double d = Double.parseDouble(str); if (Double.isInfinite(d) || Double.isNaN(d)) { throw new NumberFormatException("Invalid double value: " + str); } return d; }
@Test public void shouldThrowIfNotNumber() { assertThrows(NumberFormatException.class, () -> SqlDoubles.parseDouble("What no number?")); }
@Override public IConfigContext getConfigContext() { return configContext; }
@Test void testGetConfigContext() { ConfigRequest configRequest = new ConfigRequest(); IConfigContext configContext = configRequest.getConfigContext(); assertNotNull(configContext); }
public final void addSource(final Topology.AutoOffsetReset offsetReset, final String name, final TimestampExtractor timestampExtractor, final Deserializer<?> keyDeserializer, final Deserialize...
@Test public void shouldNotAllowOffsetResetSourceWithoutTopics() { assertThrows(TopologyException.class, () -> builder.addSource(Topology.AutoOffsetReset.EARLIEST, "source", null, stringSerde.deserializer(), stringSerde.deserializer())); }
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testReadFieldsIndividualStrings() { String[] readFields = {"f1", "f2"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, null, null, readFields, threeIntTupleType, threeIntTupleType); ...
public List<Issue> validateMetadata(ExtensionVersion extVersion) { return Observation.createNotStarted("ExtensionValidator#validateMetadata", observations).observe(() -> { var issues = new ArrayList<Issue>(); checkVersion(extVersion.getVersion(), issues); checkTargetPlatform(...
@Test public void testInvalidTargetPlatform() { var extension = new ExtensionVersion(); extension.setTargetPlatform("debian-x64"); extension.setVersion("1.0.0"); var issues = validator.validateMetadata(extension); assertThat(issues).hasSize(1); assertThat(issues.get(0...
@Override public T getValue() { return transform(base.getValue()); }
@Test public void returnsATransformedValue() { assertThat(gauge2.getValue()) .isEqualTo(3); }
public static <T> StateSerializerProvider<T> fromPreviousSerializerSnapshot( TypeSerializerSnapshot<T> stateSerializerSnapshot) { return new LazilyRegisteredStateSerializerProvider<>(stateSerializerSnapshot); }
@Test void testLazyInstantiationOfPreviousSchemaSerializer() { // create the provider with an exception throwing snapshot; // this would throw an exception if the restore serializer was eagerly accessed StateSerializerProvider<String> testProvider = StateSerializerProvider.fr...
@Override public ApiResult<TopicPartition, ListOffsetsResultInfo> handleResponse( Node broker, Set<TopicPartition> keys, AbstractResponse abstractResponse ) { ListOffsetsResponse response = (ListOffsetsResponse) abstractResponse; Map<TopicPartition, ListOffsetsResultInfo>...
@Test public void testHandleResponseSanityCheck() { TopicPartition errorPartition = t0p0; Map<TopicPartition, Long> specsByPartition = new HashMap<>(offsetTimestampsByPartition); specsByPartition.remove(errorPartition); ApiResult<TopicPartition, ListOffsetsResultInfo> result = ...
protected static boolean compareUpdateAttributes(String left, String right) { //the numbers below come from the CPE Matching standard //Table 6-2: Enumeration of Attribute Comparison Set Relations //https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nistir7696.pdf if (left.equalsIgnoreCase(rig...
@Test public void testcompareUpdateAttributes() throws CpeValidationException { assertTrue(VulnerableSoftware.compareUpdateAttributes("update1", "u1")); assertTrue(VulnerableSoftware.compareUpdateAttributes("u1", "update1")); assertTrue(VulnerableSoftware.compareUpdateAttributes("u1", "upda...
public void addProperty(String key, String value) { store.put(key, value); }
@Test void getBoolean() { memConfig.addProperty("a", Boolean.TRUE.toString()); Assertions.assertTrue(memConfig.getBoolean("a")); Assertions.assertFalse(memConfig.getBoolean("b", false)); Assertions.assertTrue(memConfig.getBoolean("b", Boolean.TRUE)); }
public static InstanceAssignmentConfig getInstanceAssignmentConfig(TableConfig tableConfig, InstancePartitionsType instancePartitionsType) { Preconditions.checkState(allowInstanceAssignment(tableConfig, instancePartitionsType), "Instance assignment is not allowed for the given table config"); // ...
@Test public void testGetInstanceAssignmentConfigWhenInstanceAssignmentConfig() { Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = new HashMap<>(); instanceAssignmentConfigMap.put(InstancePartitionsType.COMPLETED.name(), getInstanceAssignmentConfig(InstanceAssignmentConfig.Partition...
@Override public void authenticate(Invocation invocation, URL url) throws RpcAuthenticationException { String accessKeyId = String.valueOf(invocation.getAttachment(Constants.AK_KEY)); String requestTimestamp = String.valueOf(invocation.getAttachment(Constants.REQUEST_TIMESTAMP_KEY)); String ...
@Test void testAuthenticateRequestNoSignature() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk"); ...
private DeviceKeyId() { super(); }
@Test public void testConstruction() { DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue1); assertNotNull("The deviceKeyId should not be null.", deviceKeyId); assertEquals("The id should match the expected value.", deviceKeyIdValue1, deviceKeyId.id()); ...
void importPlaylistItems( List<MusicPlaylistItem> playlistItems, IdempotentImportExecutor executor, UUID jobId, TokensAndUrlAuthData authData) throws Exception { if (playlistItems != null && !playlistItems.isEmpty()) { Map<String, List<MusicPlaylistItem>> playlistItemsByPlaylist ...
@Test public void failOnePlaylistItem() throws Exception { importPlaylistSetUp("p1_id", "p1_title"); importPlaylistSetUp("p2_id", "p2_title"); MusicPlaylistItem playlistItem1 = new MusicPlaylistItem( new MusicRecording( "item1_isrc", null, 180000L, new MusicRelease("r1...
public void open( VariableSpace space, Process sqlldrProcess ) throws KettleException { String loadMethod = meta.getLoadMethod(); try { OutputStream os; if ( OraBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals( loadMethod ) ) { os = sqlldrProcess.getOutputStream(); } else { // Els...
@Test public void testOpen() { try { String tmpDir = System.getProperty("java.io.tmpdir"); File tempFile = File.createTempFile("orafiles", "test" ); String tempFilePath = tempFile.getAbsolutePath(); String dataFileVfsPath = "file:///" + tempFilePath; LocalFile tempFileObject = mock( ...
Object getCellValue(Cell cell, Schema.FieldType type) { ByteString cellValue = cell.getValue(); int valueSize = cellValue.size(); switch (type.getTypeName()) { case BOOLEAN: checkArgument(valueSize == 1, message("Boolean", 1)); return cellValue.toByteArray()[0] != 0; case BYTE: ...
@Test public void shouldParseInt16Type() { byte[] value = new byte[] {2, 0}; assertEquals((short) 512, PARSER.getCellValue(cell(value), INT16)); }
@UdafFactory(description = "collect distinct values of a Bigint field into a single Array") public static <T> Udaf<T, List<T>, List<T>> createCollectSetT() { return new Collect<>(); }
@Test public void shouldRespectSizeLimit() { final Udaf<Integer, List<Integer>, List<Integer>> udaf = CollectSetUdaf.createCollectSetT(); ((Configurable) udaf).configure(ImmutableMap.of(CollectSetUdaf.LIMIT_CONFIG, 1000)); List<Integer> runningList = udaf.initialize(); for (int i = 1; i < 2500; i++) {...
static void parseServerIpAndPort(Connection connection, Span span) { try { URI url = URI.create(connection.getMetaData().getURL().substring(5)); // strip "jdbc:" String remoteServiceName = connection.getProperties().getProperty("zipkinServiceName"); if (remoteServiceName == null || "".equals(remot...
@Test void parseServerIpAndPort_serviceNameFromDatabaseName() throws SQLException { setupAndReturnPropertiesForHost("1.2.3.4"); when(connection.getCatalog()).thenReturn("mydatabase"); TracingStatementInterceptor.parseServerIpAndPort(connection, span); verify(span).remoteServiceName("mysql-mydatabase")...
@Override public Object getValue(final int columnIndex, final Class<?> type) throws SQLException { if (boolean.class == type) { return resultSet.getBoolean(columnIndex); } if (byte.class == type) { return resultSet.getByte(columnIndex); } if (short.cla...
@Test void assertGetValueByByte() throws SQLException { ResultSet resultSet = mock(ResultSet.class); when(resultSet.getByte(1)).thenReturn((byte) 0x00); assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, byte.class), is((byte) 0x00)); }
@Override public void batchRegisterService(String serviceName, String groupName, List<Instance> instances) { throw new UnsupportedOperationException( "Do not support persistent instances to perform batch registration methods."); }
@Test void testBatchRegisterService() { assertThrows(UnsupportedOperationException.class, () -> { clientProxy.batchRegisterService("a", "b", null); }); }
List<Endpoint> endpoints() { try { String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace); return enrichWithPublicAddresses(parsePodsList(callGet(urlString))); } catch (RestClientException e) { return handleKnownException(e); ...
@Test public void wrongApiToken() { // given String unauthorizedBody = "\"reason\":\"Unauthorized\""; stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), HttpURLConnection.HTTP_UNAUTHORIZED, unauthorizedBody); // when List<Endpoint> result = kubernetesClient.endpoin...
public <T> T submitRequest(String pluginId, String requestName, PluginInteractionCallback<T> pluginInteractionCallback) { if (!pluginManager.isPluginOfType(extensionName, pluginId)) { throw new RecordNotFoundException(format("Did not find '%s' plugin with id '%s'. Looks like plugin is missing", exte...
@Test void shouldConstructTheRequest() { final String requestBody = "request_body"; when(response.responseCode()).thenReturn(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE); final GoPluginApiRequest[] generatedRequest = {null}; doAnswer(invocationOnMock -> { generatedRequest...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { if (Objects.isNull(rule)) { return Mono.empty(); } final ShenyuContext shenyuContext = ...
@Test public void testSpringCloudPluginNotConfigServiceId() { final SelectorData selectorData = SelectorData.builder() .id("springcloud") .handle("[]") .build(); final RuleData rule = RuleData.builder() .id("springcloud") ...
@Override public String version() { return AppInfoParser.getVersion(); }
@Test public void testCastVersionRetrievedFromAppInfoParser() { assertEquals(AppInfoParser.getVersion(), xformKey.version()); assertEquals(AppInfoParser.getVersion(), xformValue.version()); assertEquals(xformKey.version(), xformValue.version()); }
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowStorageUnitsStatement sqlStatement, final ContextManager contextManager) { Collection<LocalDataQueryResultRow> result = new LinkedList<>(); for (Entry<String, StorageUnit> entry : getToBeShownStorageUnits(sqlStatement).entrySet()...
@Test void assertGetRowsWithLikePattern() { Collection<LocalDataQueryResultRow> actual = executor.getRows(new ShowStorageUnitsStatement(mock(DatabaseSegment.class), "_0", null), mock(ContextManager.class)); assertThat(actual.size(), is(1)); LocalDataQueryResultRow row = actual.iterator().nex...
@Override @CacheEvict(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#id") public void deleteMailAccount(Long id) { // 校验是否存在账号 validateMailAccountExists(id); // 校验是否存在关联模版 if (mailTemplateService.getMailTemplateCountByAccountId(id) > 0) { throw exception(MAIL_ACCOUNT...
@Test public void testDeleteMailAccount_success() { // mock 数据 MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class); mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbMailAccount.getId(); // mock 方法(无关联模版) when(mailTempl...
public PatchTree generatePatchTree() { try { return new PatchTree( _patchTree.getDataMap().copy()); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Error copying data map: " + _patchTree.getDataMap(), e); } }
@Test public void testEmptyPatch() { PatchTreeRecorder<PatchTreeTestModel> pc = makeOne(); Assert.assertEquals(pc.generatePatchTree().getDataMap(), new DataMap()); }
public MessageType convert(Schema avroSchema) { if (!avroSchema.getType().equals(Schema.Type.RECORD)) { throw new IllegalArgumentException("Avro schema must be a record."); } return new MessageType(avroSchema.getFullName(), convertFields(avroSchema.getFields(), "")); }
@Test(expected = IllegalArgumentException.class) public void testParquetMapWithNonStringKeyFails() throws Exception { MessageType parquetSchema = MessageTypeParser.parseMessageType("message myrecord {\n" + " required group mymap (MAP) {\n" + " repeated group map (MAP_KEY_VALUE) {\n" ...
public void createOrUpdateTableUsingBqManifestFile(String tableName, String bqManifestFileUri, String sourceUriPrefix, Schema schema) { try { String withClauses = String.format("( %s )", BigQuerySchemaResolver.schemaToSqlString(schema)); String extraOptions = "enable_list_inference=true,"; if (!St...
@Test void createTableWithManifestFile_partitioned() throws Exception { properties.setProperty(BigQuerySyncConfig.BIGQUERY_SYNC_BIG_LAKE_CONNECTION_ID.key(), "my-project.us.bl_connection"); BigQuerySyncConfig config = new BigQuerySyncConfig(properties); client = new HoodieBigQuerySyncClient(config, mockBi...
public static FeatureRange buildFromMixedIn(String key, List<String> partitions, int arity) { Long fromInclusive = null; Long toInclusive = null; long from = 0; long to = 0; for (String p : partitions) { String[] parts = p.split(","); if (parts.length == 1...
@Test void requireThatFeatureRangeCanBeBuiltFromMixedInNode() { assertEquals(new FeatureRange("foo", 10L, 19L), FeatureRange.buildFromMixedIn("foo", List.of("foo=10-19"), 10)); assertEquals(new FeatureRange("foo", -19L, -10L), FeatureRange.buildFromMixedIn("foo", List...
public AlertResult send(String title, String content) { AlertResult alertResult = new AlertResult(); // if there is no receivers && no receiversCc, no need to process if (CollectionUtils.isEmpty(emailParams.getReceivers())) { logger.error("no receivers , you must set receivers"); ...
@Ignore @Test public void testTextSendMails() throws GeneralSecurityException { AlertResult alertResult = emailSender.send(AlertBaseConstant.ALERT_TEMPLATE_TITLE, AlertBaseConstant.ALERT_TEMPLATE_MSG); Assert.assertEquals(true, alertResult.getSuccess()); }
public static List<String> parse(@Nullable String input, boolean escapeComma, boolean trim) { if (null == input || input.isEmpty()) { return Collections.emptyList(); } Stream<String> tokenStream; if (escapeComma) { // Use regular expression to split on "," unless it is "\," // Use a n...
@Test public void testEscapeTrueTrimTrue() { String input = " \\,.\n\t()[]{}\"':=-_$\\?@&|#+/,:=[]$@&|#"; List<String> expectedOutput = Arrays.asList(",.\n\t()[]{}\"':=-_$\\?@&|#+/", ":=[]$@&|#"); Assert.assertEquals(CsvParser.parse(input, true, true), expectedOutput); }
@Override public boolean isContainer(final Path file) { if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(host))) { return super.isContainer(file); } return false; }
@Test public void testContainerVirtualHostInHostname() { assertFalse("/", new S3PathContainerService(new Host(new S3Protocol(), "b.s3.amazonaws.com")).isContainer(new Path("/b", EnumSet.of(Path.Type.directory)))); assertFalse("/", new S3PathContainerService(new Host(new S3Protocol(), "b.s3.amazonaws...
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = ...
@Test void test_realize_IntPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setInt", int.class); assertNotNull(method); Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); ...
public static NoActionInstruction createNoAction() { return new NoActionInstruction(); }
@Test public void testCreateNoActionMethod() { Instructions.NoActionInstruction instruction = Instructions.createNoAction(); checkAndConvert(instruction, Instruction.Type.NOACTION, Instructions.NoActionInstruction.class); }
public static void main(String[] args) throws IOException { runSqlLine(args, null, System.out, System.err); }
@Test public void testSqlLine_ddl() throws Exception { BeamSqlLine.main( new String[] { "-e", "CREATE EXTERNAL TABLE test (id INTEGER) TYPE 'text';", "-e", "DROP TABLE test;" }); }
@Override public void createTable(Table table) { validateTableType(table); // first assert the table name is unique if (tables.containsKey(table.getName())) { throw new IllegalArgumentException("Duplicate table name: " + table.getName()); } // invoke the provider's create providers.get...
@Test(expected = IllegalArgumentException.class) public void testCreateTable_invalidTableType() throws Exception { Table table = mockTable("person", "invalid"); store.createTable(table); }
@Override public void onStateElection(Job job, JobState newState) { if (isNotFailed(newState) || isJobNotFoundException(newState) || isProblematicExceptionAndMustNotRetry(newState) || maxAmountOfRetriesReached(job)) return; job.scheduleAt(now().plusSeconds(getSecondsToAdd(job)), String....
@Test void retryFilterSchedulesJobAgainIfStateIsFailed() { final Job job = aFailedJob().build(); applyDefaultJobFilter(job); int beforeVersion = job.getJobStates().size(); retryFilter.onStateElection(job, job.getJobState()); int afterVersion = job.getJobStates().size(); ...
public Optional<String> removeStreamThread() { return removeStreamThread(Long.MAX_VALUE); }
@Test public void shouldNotRemoveThreadWhenNotRunning() { prepareStreams(); prepareStreamThread(streamThreadOne, 1); props.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1); try (final KafkaStreams streams = new KafkaStreams(getBuilderWithSource().build(), props, s...
public final int queueCount() { return queues.length; }
@Test public void queueCount() { assertEquals(queueCount, conveyor.queueCount()); }
@Override public Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst) { checkNotNull(src, DEVICE_ID_NULL); checkNotNull(dst, DEVICE_ID_NULL); return defaultTopology(topology).getPaths(src, dst); }
@Test public void testGetPaths() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVi...
@Udf(description = "Converts a string representation of a time in the given format" + " into the TIME value.") public Time parseTime( @UdfParameter( description = "The string representation of a time.") final String formattedTime, @UdfParameter( description = "The format pattern ...
@Test public void shouldConvertStringToDate() { // When: final Time result = udf.parseTime("000105", "HHmmss"); // Then: assertThat(result.getTime(), is(65000L)); }
public static String getBaseUrl() { try { var requestAttrs = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); return getBaseUrl(requestAttrs.getRequest()); } catch (IllegalStateException e) { // method is called outside of web request contex...
@Test public void testWithXForwarded() throws Exception { // basic request doReturn("http").when(request).getScheme(); doReturn("localhost").when(request).getServerName(); doReturn(8080).when(request).getServerPort(); doReturn("/").when(request).getContextPath(); // ...
@Override public boolean isReachable(DeviceId deviceId) { SnmpDevice snmpDevice = controller.getDevice(deviceId); if (snmpDevice == null) { log.warn("BAD REQUEST: the requested device id: " + deviceId.toString() + " is not associ...
@Test public void addDevice() { AbstractProjectableModel.setDriverService(null, new MockDriverService()); //FIXME this needs sleep assertAfter(DELAY, TEST_DURATION, () -> assertNotNull("Device should be added to controller", controller.getDevice(deviceId))); assertTru...
@Override public boolean shouldWait() { RingbufferContainer ringbuffer = getRingBufferContainerOrNull(); if (resultSet == null) { resultSet = new ReadResultSetImpl<>(minSize, maxSize, getNodeEngine().getSerializationService(), filter); sequence = startSequence; } ...
@Test public void whenOneAfterTailAndBufferEmpty() { ReadManyOperation op = getReadManyOperation(ringbuffer.tailSequence() + 1, 1, 1, null); // since there is an item, we don't need to wait boolean shouldWait = op.shouldWait(); assertTrue(shouldWait); ReadResultSetImpl resp...
public static <T extends com.google.protobuf.GeneratedMessageV3> ProtobufSchema<T> of(Class<T> pojo) { return of(pojo, new HashMap<>()); }
@Test public void testSchema() { ProtobufSchema<org.apache.pulsar.client.schema.proto.Test.TestMessage> protobufSchema = ProtobufSchema.of(org.apache.pulsar.client.schema.proto.Test.TestMessage.class); Assert.assertEquals(protobufSchema.getSchemaInfo().getType(), SchemaType.PROTOBUF...
@Override public void operate() { // Drain and create new autorelease pool impl.operate(); }
@Test public void testOperate() { new AutoreleaseActionOperationBatcher(1).operate(); }
void onSignal(final long correlationId, final long recordingId, final long position, final RecordingSignal signal) { if (correlationId == replicationId) { if (RecordingSignal.EXTEND == signal) { final CountersReader counters = archive.context().aeron().counter...
@Test void shouldFailIfRecordingLogIsDeletedDuringReplication() { final RecordingSignal recordingSignal = RecordingSignal.DELETE; final long stopPosition = 982734; final long nowNs = 0; final ReplicationParams replicationParams = new ReplicationParams() .dstRecording...
@Override public EnvironmentConfig getLocal() { for (EnvironmentConfig part : this) { if (part.isLocal()) return part; } return null; }
@Test void shouldGetLocalPartWhenOriginFile() { assertThat(environmentConfig.getLocal()).isEqualTo(uatLocalPart2); }
public IterationResult<T> iterate(@Nonnull UUID cursorId, int maxCount) { requireNonNull(cursorId); if (cursorId.equals(this.prevCursorId)) { access(); // no progress, no need to forget a cursor id, so null return new IterationResult<>(this.page, this.cursorId, null);...
@Test public void testCursorIdOtherThan_PreviousOrCurrent_Throws() { UUID cursorId = iterator.iterate(initialCursorId, 100).getCursorId(); iterator.iterate(cursorId, 100); // prevCursorId == cursorId, cursorId == new id assertThatThrownBy(() -> iterator.iterate(initialCursorId, 100))...
@Override public void clear() { root = null; size = 0; modCount++; // Clear iteration order Node<K, V> header = this.header; header.next = header.prev = header; }
@Test public void testClear() { LinkedTreeMap<String, String> map = new LinkedTreeMap<>(); map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); map.clear(); assertThat(map.keySet()).isEmpty(); assertThat(map).isEmpty(); }
@Activate public void activate(ComponentContext context) { active = true; componentConfigService.registerProperties(getClass()); providerService = providerRegistry.register(this); coreService.registerApplication(APP_NAME); cfgService.registerConfigFactory(factory); cf...
@Test public void activate() throws Exception { assertTrue("Provider should be registered", deviceRegistry.getProviders().contains(provider.id())); assertEquals("Incorrect device service", deviceService, provider.deviceService); assertEquals("Incorrect provider service", providerService, pro...
public static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins) throws URISyntaxException { URI toRet = null; for(TrackingUriPlugin plugin : trackingUriPlugins) { toRet = plugin.getTrackingUri(id); if (toRet != null) { return to...
@Test void testGetProxyUriFromPluginsReturnsValidUriWhenAble() throws URISyntaxException { ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); List<TrackingUriPlugin> list = Lists.newArrayListWithExpectedSize(2); // Insert a plugin that returns null. list.add(new TrackingUriPl...
public static void setIpAddress(String ipAddress) { XID.ipAddress = ipAddress; }
@Test public void testSetIpAddress() { XID.setIpAddress("127.0.0.1"); assertThat(XID.getIpAddress()).isEqualTo("127.0.0.1"); }
public static <T> boolean isNotEmpty(T[] array) { return (null != array && array.length != 0); }
@Test public void isNotEmptyTest() { int[] a = {1, 2}; assertTrue(ArrayUtil.isNotEmpty(a)); String[] b = {"a", "b", "c"}; assertTrue(ArrayUtil.isNotEmpty(b)); Object c = new Object[]{"1", "2", 3, 4D}; assertTrue(ArrayUtil.isNotEmpty(c)); }
public List<HostAddress> toHostAddressList(Collection<Host> hosts) { ArrayList<HostAddress> list = new ArrayList<>(hosts.size()); for (Host host : hosts) { list.add(toHostAddress(host)); } return list; }
@Test public void testToHostAddressList() throws Exception { Set<Host> hosts = ImmutableSet.of( new TestHost( new InetSocketAddress( InetAddress.getByAddress(new byte[] { 1, 2, 3, ...
static EfestoOutputPMML getEfestoOutput(KiePMMLModelFactory kiePMMLModelFactory, EfestoInputPMML darInputPMML) { List<KiePMMLModel> kiePMMLModels = kiePMMLModelFactory.getKiePMMLModels(); PMML4Result result = evaluate(kiePMMLModels, darInputPMML.getInputData()); return new EfestoOutputPMML(darIn...
@Test void getEfestoOutput() { modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME); PMMLRuntimeContext pmmlContext = getPMMLContext(FILE_NAME, MODEL_NAME, memoryCompilerClassLoader); KiePMMLModelFactory kiePmmlModelFactory = PMMLLoaderUtils.loadKiePMMLModelFactory(m...
public static <T> CloseableIterator<T> wrap(CloseableIterator<T> iterator, AutoCloseable... otherCloseables) { return new CloseablesIteratorWrapper<>(iterator, otherCloseables); }
@Test(expected = IllegalArgumentException.class) public void wrap_fails_if_iterator_declared_in_other_closeables() { CloseableIterator iterator = new SimpleCloseableIterator(); CloseableIterator.wrap(iterator, iterator); }
public void handleRequestBody(String requestBody, String userUuid, ProjectDto projectDto) { // parse anticipated transitions from request body List<AnticipatedTransition> anticipatedTransitions = anticipatedTransitionParser.parse(requestBody, userUuid, projectDto.getKey()); try (DbSession dbSession = dbCli...
@Test public void fivenRequestBodyWithTransitions_whenHandleRequestBody_thenTransitionsAreInserted() { // given ProjectDto projectDto = new ProjectDto() .setKey(PROJECT_KEY); String requestBody = "body_with_transitions"; doReturn(List.of(populateAnticipatedTransition(), populateAnticipatedTrans...
public static void sliceByRowsAndCols(File srcImageFile, File destDir, int rows, int cols) { sliceByRowsAndCols(srcImageFile, destDir, IMAGE_TYPE_JPEG, rows, cols); }
@Test @Disabled public void sliceByRowsAndColsTest2() { ImgUtil.sliceByRowsAndCols( FileUtil.file("d:/test/hutool.png"), FileUtil.file("d:/test/dest"), ImgUtil.IMAGE_TYPE_PNG, 1, 5); }
@Override public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final SelectionParameters other = (SelectionParamet...
@Test public void testEqualsResultTypeOneNull() { List<String> qualifyingNames = Arrays.asList( "language", "german" ); TypeMirror resultType = new TestTypeMirror( "resultType" ); List<TypeMirror> qualifiers = new ArrayList<>(); qualifiers.add( new TestTypeMirror( "org.mapstruct.test...