focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String toString() { return "(name=" + name + ", numPartitions=" + numPartitions.map(String::valueOf).orElse("default") + ", replicationFactor=" + replicationFactor.map(String::valueOf).orElse("default") + ", replicasAssignments=" + replicasAss...
@Test public void testToString() { NewTopic topic1 = new NewTopic(TEST_TOPIC, NUM_PARTITIONS, REPLICATION_FACTOR); String expected1 = "(name=" + TEST_TOPIC + ", numPartitions=" + NUM_PARTITIONS + ", replicationFactor=" + REPLICATION_FACTOR + ", replicasAssignments=null, configs=null)...
public Object getValue(Integer index) throws IOException { Map<Integer, COSObjectable> numbers = getNumbers(); if (numbers != null) { return numbers.get(index); } Object retval = null; List<PDNumberTreeNode> kids = getKids(); if (kids != null) ...
@Test void testGetValue() throws IOException { assertEquals(new PDTest( 51 ), this.node5.getValue( 4 )); assertEquals(new PDTest(70), this.node1.getValue( 9 )); this.node1.setKids( null ); this.node1.setNumbers( null ); assertNull( this.node1.getValue( 0 ) ); ...
@Override public void processElement(StreamRecord<E> element) throws Exception { final E externalRecord = element.getValue(); final Object internalRecord; try { internalRecord = converter.toInternal(externalRecord); } catch (Exception e) { throw new FlinkRunt...
@Test public void testInvalidEventTime() { final InputConversionOperator<Row> operator = new InputConversionOperator<>( createConverter(DataTypes.ROW(DataTypes.FIELD("f", DataTypes.INT()))), false, true, ...
@Override public double p(double x) { if (x <= 0) { return 0.0; } else { return Math.exp(logp(x)); } }
@Test public void testP() { System.out.println("p"); ChiSquareDistribution instance = new ChiSquareDistribution(20); instance.rand(); assertEquals(0.0, instance.p(0), 1E-7); assertEquals(2.559896e-18, instance.p(0.1), 1E-22); assertEquals(1.632262e-09, instance.p(1), ...
@POST @Timed @Path("tables/{idOrName}/purge") @ApiOperation(value = "Purge Lookup Table Cache on the cluster-wide level") @NoAuditEvent("Cache purge only") @RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ) public Map<String, CallResult<Void>> performPurge( @ApiParam(name = "id...
@Test public void performPurge_whenOneHttpCallFailsThenResponseWithPerNodeDetailsReturned() throws Exception { // given when(nodeService.allActive()).thenReturn(nodeMap()); mock204Response("testName", "testKey", remoteLookupTableResource1); mock404Response("testName", "testKey", remo...
private static Schema optional(Schema original) { // null is first in the union because Parquet's default is always null return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), original)); }
@Test public void testOptionalMapValue() throws Exception { Schema schema = Schema.createRecord("record1", null, null, false); Schema optionalIntMap = Schema.createMap(optional(Schema.create(INT))); schema.setFields(Arrays.asList(new Schema.Field("myintmap", optionalIntMap, null, null))); testRoundTri...
private QueryStateInfo getQueryStateInfo( BasicQueryInfo queryInfo, boolean includeAllQueryProgressStats, boolean excludeResourceGroupPathInfo, OptionalInt queryTextSizeLimit) { Optional<ResourceGroupId> groupId = queryInfo.getResourceGroupId(); return...
@Test public void testGetQueryStateInfo() { QueryStateInfo info = client.execute( prepareGet().setUri(server.resolve("/v1/queryState/" + queryResults.getId())).build(), createJsonResponseHandler(jsonCodec(QueryStateInfo.class))); assertNotNull(info); }
@Override public FastAppend appendFile(DataFile file) { Preconditions.checkNotNull(file, "Invalid data file: null"); if (newFilePaths.add(file.path())) { this.hasNewFiles = true; newFiles.add(file); summaryBuilder.addedFile(spec, file); } return this; }
@TestTemplate public void testEmptyTableAppend() { assertThat(listManifestFiles()).isEmpty(); TableMetadata base = readMetadata(); assertThat(base.currentSnapshot()).isNull(); assertThat(base.lastSequenceNumber()).isEqualTo(0); table.newFastAppend().appendFile(FILE_A).appendFile(FILE_B).commit()...
public int getCurrentConnectionCount() { return this.connections.size(); }
@Test void testGetCurrentConnectionCount() { assertEquals(1, connectionManager.getCurrentConnectionCount()); }
@POST @Path("/{connector}/tasks/{task}/restart") @Operation(summary = "Restart the specified task for the specified connector") public void restartTask(final @PathParam("connector") String connector, final @PathParam("task") Integer task, final @Contex...
@Test public void testRestartTaskOwnerRedirect() throws Throwable { ConnectorTaskId taskId = new ConnectorTaskId(CONNECTOR_NAME, 0); final ArgumentCaptor<Callback<Void>> cb = ArgumentCaptor.forClass(Callback.class); String ownerUrl = "http://owner:8083"; expectAndCallbackException(c...
public static PartitionKey createPartitionKey(List<String> values, List<Column> columns) throws AnalysisException { return createPartitionKey(values, columns, Table.TableType.HIVE); }
@Test public void testCreatePartitionKey() throws Exception { PartitionKey partitionKey = createPartitionKey( Lists.newArrayList("1", "a", "3.0", HiveMetaClient.PARTITION_NULL_VALUE), partColumns); Assert.assertEquals("(\"1\", \"a\", \"3.0\", \"NULL\")", partitionKey.toSql()); }
public static String compactLinkString(Link link) { return String.format(COMPACT, link.src().elementId(), link.src().port(), link.dst().elementId(), link.dst().port()); }
@Test public void linkStringBahFu() { String compact = TopoUtils.compactLinkString(LINK_BAH_FU); assertEquals("wrong link id", "bah:002/5-fu:001/3", compact); }
@Override public void run() { // initialize the thread context ThreadContext.put("function", WindowUtils.getFullyQualifiedName( context.getTenant(), context.getNamespace(), context.getFunctionName())); try { long waterMarkTs = computeWaterMarkTs(); if ...
@Test public void testNoEvents() throws Exception { waterMarkEventGenerator.run(); assertTrue(eventList.isEmpty()); }
public boolean fence(HAServiceTarget fromSvc) { return fence(fromSvc, null); }
@Test public void testSingleFencer() throws BadFencingConfigurationException { NodeFencer fencer = setupFencer( AlwaysSucceedFencer.class.getName() + "(foo)"); assertTrue(fencer.fence(MOCK_TARGET)); assertEquals(1, AlwaysSucceedFencer.fenceCalled); assertSame(MOCK_TARGET, AlwaysSucceedFencer.f...
@Override @MethodNotAvailable public void putTransient(K key, V value, long ttl, TimeUnit timeunit) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testPutTransient() { adapter.putTransient(42, "value", 1, TimeUnit.MILLISECONDS); }
@VisibleForTesting static List<Set<PlanFragmentId>> extractPhases(Collection<PlanFragment> fragments) { // Build a graph where the plan fragments are vertexes and the edges represent // a before -> after relationship. For example, a join hash build has an edge // to the join probe. ...
@Test public void testExchange() { PlanFragment aFragment = createTableScanPlanFragment("a"); PlanFragment bFragment = createTableScanPlanFragment("b"); PlanFragment cFragment = createTableScanPlanFragment("c"); PlanFragment exchangeFragment = createExchangePlanFragment("exchange...
@Override public CompletableFuture<Map<String, BrokerLookupData>> filterAsync(Map<String, BrokerLookupData> availableBrokers, ServiceUnitId serviceUnit, LoadManagerContext ...
@Test public void testFilterWithPersistentOrNonPersistentDisabled() throws IllegalAccessException, BrokerFilterException, ExecutionException, InterruptedException { var namespace = "my-tenant/my-ns"; NamespaceName namespaceName = NamespaceName.get(namespace); NamespaceBundle name...
public Map<Uuid, Set<Integer>> partitionsPendingRevocation() { return partitionsPendingRevocation; }
@Test public void testUpdateWithConsumerGroupCurrentMemberAssignmentValue() { Uuid topicId1 = Uuid.randomUuid(); Uuid topicId2 = Uuid.randomUuid(); ConsumerGroupCurrentMemberAssignmentValue record = new ConsumerGroupCurrentMemberAssignmentValue() .setMemberEpoch(10) ...
public String generateSignature() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.serialSigType"), x509cert.getSigAlgName()); append(builder, NLS.str("certificate.serialSigOID"), x509cert.getSigAlgOID()); return builder.toString(); }
@Test public void decodeDSAKeySignature() { assertThat(certificateManagerDSA.generateSignature()) .contains("SHA1withDSA") .contains("1.2.840.10040.4.3"); }
static File resolveLocalFile(String input) { return resolveLocalFile(input, LOCAL_FILES_BASE_DIR); }
@Test public void testResolveLocalFile() throws Exception { assertEquals(ConfigShell.resolveLocalFile("myfile").getAbsolutePath(), new File("myfile").getAbsolutePath()); assertEquals(ConfigShell.resolveLocalFile("mydir/myfile.txt").getAbsolutePath(), new File("mydir/m...
@Override public void getErrors(ErrorCollection errors, String parentLocation) { String location = this.getLocation(parentLocation); if (new NameTypeValidator().isNameInvalid(name)) { errors.addError(location, NameTypeValidator.errorMessage("parameter", name)); } }
@Test public void shouldAddAnErrorIfParameterNameIsBlank() { CRParameter crParameter = new CRParameter(); ErrorCollection errorCollection = new ErrorCollection(); crParameter.getErrors(errorCollection, "TEST"); assertThat(errorCollection.getErrorsAsText()).contains("Invalid paramete...
@Override public synchronized void startInternal() throws LifecycleException { try { // direct coupling with LogbackValve implementation FieldUtils.writeField(this, "scheduledExecutorService", ExecutorServiceUtil.newScheduledExecutorService(), true); FieldUtils.writeField(this, "started", true, ...
@Test public void startInternal() throws Exception { ProgrammaticLogbackValve valve = new ProgrammaticLogbackValve(); valve.setContainer(mock(Container.class)); valve.start(); assertThat(valve.isStarted()).isTrue(); valve.stop(); assertThat(valve.isStarted()).isFalse(); }
public static void openSystemSettingsLoginItems() { CLASS.openSystemSettingsLoginItems(); }
@Test public void testSettings() { assumeFalse(Factory.Platform.osversion.matches("(10|11|12)\\..*")); SMAppService.openSystemSettingsLoginItems(); }
public static void createFileIfAbsent(File file, boolean isDir) throws IOException { if (file.exists()) { return; } boolean createResult = isDir ? file.mkdirs() : file.createNewFile(); if (!createResult && !file.exists()) { throw new IllegalStateException("failed ...
@Test void testCreateFileIfAbsentForFile() throws Throwable { assertThrows(IllegalStateException.class, () -> { File file = mock(File.class); DiskCache.createFileIfAbsent(file, false); }); }
@Override public PageResult<MailTemplateDO> getMailTemplatePage(MailTemplatePageReqVO pageReqVO) { return mailTemplateMapper.selectPage(pageReqVO); }
@Test public void testGetMailTemplatePage() { // mock 数据 MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class, o -> { // 等会查询到 o.setName("源码"); o.setCode("test_01"); o.setAccountId(1L); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); ...
@Udf public <T> Boolean contains( @UdfParameter final String jsonArray, @UdfParameter final T val ) { try (JsonParser parser = PARSER_FACTORY.createParser(jsonArray)) { if (parser.nextToken() != START_ARRAY) { return false; } while (parser.nextToken() != null) { fi...
@Test public void shouldNotFindValuesInNullArray() { assertEquals(true, jsonUdf.contains("[null]", null)); assertEquals(false, jsonUdf.contains("[null]", "null")); assertEquals(false, jsonUdf.contains("[null]", true)); assertEquals(false, jsonUdf.contains("[null]", false)); a...
@Override @CheckForNull public ScannerReport.Changesets readChangesets(int componentRef) { ensureInitialized(); return delegate.readChangesets(componentRef); }
@Test public void verify_readChangesets_returns_changesets() { writer.writeComponentChangesets(CHANGESETS); ScannerReport.Changesets res = underTest.readChangesets(COMPONENT_REF); assertThat(res).isEqualTo(CHANGESETS); }
@Override public void replay( long offset, long producerId, short producerEpoch, CoordinatorRecord record ) throws RuntimeException { ApiMessageAndVersion key = record.key(); ApiMessageAndVersion value = record.value(); switch (key.version()) { ...
@Test public void testReplayOffsetCommitWithNullValue() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class); CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class); ...
@Override public RFuture<Boolean> removeAsync(Object object) { String name = getRawName(object); return commandExecutor.writeAsync(name, codec, RedisCommands.ZREM, name, encode(object)); }
@Test public void testRemoveAsync() throws InterruptedException, ExecutionException { RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple"); set.add(0.11, 1); set.add(0.22, 3); set.add(0.33, 7); Assertions.assertTrue(set.removeAsync(1).get()); Asserti...
@Override public boolean accept(FilterableIssue issue, IssueFilterChain chain) { boolean atLeastOneRuleMatched = false; boolean atLeastOnePatternFullyMatched = false; IssuePattern matchingPattern = null; for (IssuePattern pattern : multicriteriaPatterns) { if (ruleMatches(pattern, issue.ruleKey...
@Test public void shouldAcceptIssueIfMatchesDeprecatedRuleKey() { RuleKey ruleKey = RuleKey.of("repo", "rule"); DefaultActiveRules activeRules = new DefaultActiveRules(ImmutableSet.of(new NewActiveRule.Builder() .setRuleKey(ruleKey) .setDeprecatedKeys(singleton(RuleKey.of("repo2", "deprecated"))) ...
@Override public CiConfiguration loadConfiguration() { String revision = system.envVariable("CI_COMMIT_SHA"); return new CiConfigurationImpl(revision, getName()); }
@Test public void loadConfiguration() { setEnvVariable("GITLAB_CI", "true"); setEnvVariable("CI_COMMIT_SHA", "abd12fc"); assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc"); }
@Override protected void runTask() { LOGGER.trace("Looking for orphan jobs... "); final Instant updatedBefore = runStartTime().minus(serverTimeoutDuration); processManyJobs(previousResults -> getOrphanedJobs(updatedBefore, previousResults), this::changeJobStateToFailedAndRunJ...
@Test void testTaskAndStateChangeFilters() { final Job orphanedJob = aJobInProgress().build(); when(storageProvider.getJobList(eq(PROCESSING), any(Instant.class), any())) .thenReturn( singletonList(orphanedJob), emptyJobList() ...
static BlockStmt getFalsePredicateVariableDeclaration(final String variableName, final False falsePredicate) { final MethodDeclaration methodDeclaration = FALSEPREDICATE_TEMPLATE.getMethodsByName(GETKIEPMMLFALSEPREDICATE).get(0).clone(); final BlockStmt toReturn = methodDeclaration.getBody().orElseThrow...
@Test void getFalsePredicateVariableDeclaration() throws IOException { String variableName = "variableName"; BlockStmt retrieved = KiePMMLFalsePredicateFactory.getFalsePredicateVariableDeclaration(variableName, ...
@Override public void shutDown() throws NacosException { serviceInfoHolder.shutdown(); clientProxy.shutdown(); NotifyCenter.deregisterSubscriber(changeNotifier); }
@Test void testShutDown() throws NacosException { //when client.shutDown(); //then verify(proxy, times(1)).shutdown(); }
@Override public Long getUnreadNotifyMessageCount(Long userId, Integer userType) { return notifyMessageMapper.selectUnreadCountByUserIdAndUserType(userId, userType); }
@Test public void testGetUnreadNotifyMessageCount() { SqlConstants.init(DbType.MYSQL); // mock 数据 NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> { // 等会查询到 o.setUserId(1L); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setReadSt...
public static <X extends Throwable> void isTrue(boolean expression, Supplier<? extends X> supplier) throws X { if (false == expression) { throw supplier.get(); } }
@Test public void isTrueTest2() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { int i = -1; //noinspection ConstantConditions cn.hutool.core.lang.Assert.isTrue(i >= 0, IndexOutOfBoundsException::new); }); }
boolean fillIssueInFileLocation(NewIssueLocation newIssueLocation, Location location) { PhysicalLocation physicalLocation = location.getPhysicalLocation(); String fileUri = getFileUriOrThrow(location); Optional<InputFile> file = findFile(fileUri); if (file.isEmpty()) { return false; } Inp...
@Test public void fillIssueInFileLocation_whenFileNotFound_returnsFalse() { when(sensorContext.fileSystem().inputFile(any())).thenReturn(null); boolean success = locationMapper.fillIssueInFileLocation(newIssueLocation, location); assertThat(success).isFalse(); }
public static <T> Read<T> readMessage() { return new AutoValue_JmsIO_Read.Builder<T>() .setMaxNumRecords(Long.MAX_VALUE) .setCloseTimeout(DEFAULT_CLOSE_TIMEOUT) .setRequiresDeduping(false) .build(); }
@Test public void testReadBytesMessagesWithCFProviderFn() throws Exception { long count = 5; produceTestMessages(count, JmsIOTest::createBytesMessage); PCollection<String> output = pipeline.apply( JmsIO.<String>readMessage() .withConnectionFactoryProviderFn( ...
@Override public String getName() { return FUNCTION_NAME; }
@Test public void testTruncateNullColumn() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("truncate(%s, 0)", INT_SV_NULL_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); Assert.assertTrue(transformFunction i...
@Override public String getImage() { try { if ( isLocked() ) { return "ui/images/lock.svg"; //$NON-NLS-1$ } } catch ( KettleException e ) { throw new RuntimeException( e ); } return "ui/images/transrepo.svg"; //$NON-NLS-1$ }
@Test public void testGetImage() { String image = uiTransformation.getImage(); assertNotNull( image ); File f = new File( image ); when( mockEERepositoryObject.isLocked() ).thenReturn( true ); String image2 = uiTransformation.getImage(); assertNotNull( image2 ); f = new File( image2 ); ...
long importPhotos( Collection<PhotoModel> photos, GPhotosUpload gPhotosUpload) throws Exception { return gPhotosUpload.uploadItemsViaBatching( photos, this::importPhotoBatch); }
@Test public void importTwoPhotos() throws Exception { PhotoModel photoModel1 = new PhotoModel( PHOTO_TITLE, IMG_URI, PHOTO_DESCRIPTION, JPEG_MEDIA_TYPE, "oldPhotoID1", OLD_ALBUM_ID, false, SHA1); Mockito.w...
public MaterializedConfiguration getConfiguration() { MaterializedConfiguration conf = new SimpleMaterializedConfiguration(); FlumeConfiguration fconfig = getFlumeConfiguration(); AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName()); if (agentConf != null) { ...
@Test public void testSinkSourceMismatchDuringConfiguration() throws Exception { String agentName = "agent1"; String sourceType = "seq"; String channelType = "memory"; String sinkType = "avro"; Map<String, String> properties = getProperties(agentName, sourceType, ...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testDuelArenaWin() { ChatMessage chatMessageEvent = new ChatMessage(null, TRADE, "", "You won! You have now won 1,909 duels.", null, 0); chatCommandsPlugin.onChatMessage(chatMessageEvent); chatMessageEvent = new ChatMessage(null, TRADE, "", "You have lost 1,999 duels.", null, 0); chatComman...
public static Path getCacheHome() { return getCacheHome(System.getProperties(), System.getenv()); }
@Test public void testGetCacheHome_hasXdgCacheHome() { Properties fakeProperties = new Properties(); fakeProperties.setProperty("user.home", fakeCacheHome); Map<String, String> fakeEnvironment = ImmutableMap.of("XDG_CACHE_HOME", fakeCacheHome); fakeProperties.setProperty("os.name", "linux"); Asse...
@Override public List<MailAccountDO> getMailAccountList() { return mailAccountMapper.selectList(); }
@Test public void testGetMailAccountList() { // mock 数据 MailAccountDO dbMailAccount01 = randomPojo(MailAccountDO.class); mailAccountMapper.insert(dbMailAccount01); MailAccountDO dbMailAccount02 = randomPojo(MailAccountDO.class); mailAccountMapper.insert(dbMailAccount02); ...
public void assignActiveToConsumer(final TaskId task, final String consumer) { if (!assignedActiveTasks.taskIds().contains(task)) { throw new IllegalStateException("added not assign active task " + task + " to this client state."); } assignedActiveTasks.consumerToTaskIds() ...
@Test public void shouldThrowIllegalStateExceptionIfAssignedTasksForConsumerToNonClientAssignActive() { assertThrows(IllegalStateException.class, () -> client.assignActiveToConsumer(TASK_0_0, "c1")); }
public static WalletFile createLight(String password, ECKeyPair ecKeyPair) throws CipherException { return create(password, ecKeyPair, N_LIGHT, P_LIGHT); }
@Test public void testEncryptDecryptLight() throws Exception { testEncryptDecrypt(Wallet.createLight(SampleKeys.PASSWORD, SampleKeys.KEY_PAIR)); }
public static CredentialsConfigurator get(final Protocol protocol) { final CredentialsConfigurator finder = protocol.getFeature(CredentialsConfigurator.class); try { return finder.reload(); } catch(LoginCanceledException e) { if(log.isWarnEnabled()) { ...
@Test public void testGet() { final Host host = new Host(new TestProtocol()); final Credentials credentials = host.getCredentials(); assertSame(credentials, CredentialsConfiguratorFactory.get(new TestProtocol()).configure(host)); }
public long scan( final UnsafeBuffer termBuffer, final long rebuildPosition, final long hwmPosition, final long nowNs, final int termLengthMask, final int positionBitsToShift, final int initialTermId) { boolean lossFound = false; int rebuildOff...
@Test void shouldStopNakOnReceivingData() { long rebuildPosition = ACTIVE_TERM_POSITION; final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L); insertDataFrame(offsetOfMessage(0)); insertDataFrame(offsetOfMessage(2)); lossDetector.scan(termBuffer, ...
public static Pair<CloudObjectIncrCheckpoint, Option<Dataset<Row>>> filterAndGenerateCheckpointBasedOnSourceLimit(Dataset<Row> sourceData, long sourceLimit, QueryInfo queryInfo, ...
@Test void testLastObjectInCommit() { List<Triple<String, Long, String>> filePathSizeAndCommitTime = new ArrayList<>(); // Add file paths and sizes to the list filePathSizeAndCommitTime.add(Triple.of("path/to/file1.json", 100L, "commit1")); filePathSizeAndCommitTime.add(Triple.of("path/to/file3.json",...
@Override public void watch(final String key, final DataChangedEventListener listener) { List<InstanceInfo> initialInstances = eurekaClient.getInstancesByVipAddressAndAppName(null, key, true); instanceListMap.put(key, initialInstances); for (InstanceInfo instance : initialInstances) { ...
@Test void testWatch() throws NoSuchFieldException, IllegalAccessException { final String key = "testService"; final DataChangedEventListener mockListener = mock(DataChangedEventListener.class); final List<InstanceInfo> initialInstances = new ArrayList<>(); initialInstances.add(mock(...
@Override public void dropTable(TablePath tablePath, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException { if (ignoreIfNotExists) { if (!tableExists(tablePath)) { log.info( "Attempted to drop table at path: {}. The table ...
@Test @Order(8) void dropTable() { icebergCatalog.dropTable(tablePath, false); Assertions.assertFalse(icebergCatalog.tableExists(tablePath)); }
@Override public List<String> getColumnNames(Configuration conf) throws HiveJdbcDatabaseAccessException { return getColumnMetadata(conf, ResultSetMetaData::getColumnName); }
@Test public void testGetColumnNames_fieldListQuery() throws HiveJdbcDatabaseAccessException { Configuration conf = buildConfiguration(); conf.set(JdbcStorageConfig.QUERY.getPropertyName(), "select name,referrer from test_strategy"); DatabaseAccessor accessor = DatabaseAccessorFactory.getAccessor(conf); ...
public static Failed failed(XmlPullParser parser) throws XmlPullParserException, IOException { ParserUtils.assertAtStartTag(parser); String name; StanzaError.Condition condition = null; List<StanzaErrorTextElement> textElements = new ArrayList<>(4); outerloop: while (true...
@Test public void testParseFailedError() throws Exception { StanzaError.Condition errorCondition = StanzaError.Condition.unexpected_request; String failedStanza = XMLBuilder.create("failed") .a("xmlns", "urn:xmpp:sm:3") .element(errorCondition.toString(), StanzaError...
@VisibleForTesting Entity exportNativeEntity(GrokPattern grokPattern, EntityDescriptorIds entityDescriptorIds) { final GrokPatternEntity grokPatternEntity = GrokPatternEntity.create(grokPattern.name(), grokPattern.pattern()); final JsonNode data = objectMapper.convertValue(grokPatternEntity, JsonNod...
@Test public void exportNativeEntity() { final GrokPattern grokPattern = GrokPattern.create("01234567890", "name", "pattern", null); final EntityDescriptor descriptor = EntityDescriptor.create(grokPattern.id(), ModelTypes.GROK_PATTERN_V1); final EntityDescriptorIds entityDescriptorIds = Enti...
public Group getGroup(JID jid) throws GroupNotFoundException { JID groupJID = GroupJID.fromJID(jid); return (groupJID instanceof GroupJID) ? getGroup(((GroupJID)groupJID).getGroupName()) : null; }
@Test public void aForceLookupMissWillIgnoreTheExistingCache() throws Exception { groupCache.put(GROUP_NAME, CacheableOptional.of(cachedGroup)); doThrow(new GroupNotFoundException()).when(groupProvider).getGroup(GROUP_NAME); try { groupManager.getGroup(GROUP_NAME, true); ...
@Override public StorageObject upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.ge...
@Test(expected = NotfoundException.class) public void testUploadInvalidContainer() throws Exception { final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final S3MultipartUploadService m = new S3MultipartUploadService(session, new S3WriteFeature(session, acl), acl, 5 * 10...
@Override public boolean isReference(Object bean, String beanName) { return isLocalTCC(bean); }
@Test public void testReferenceParser(){ TccActionImpl tccAction = new TccActionImpl(); boolean result = localTCCRemotingParser.isReference(tccAction, "b"); Assertions.assertTrue(result); }
public Destination[] createDestinations(int destCount) throws JMSException { final String destName = getClient().getDestName(); ArrayList<Destination> destinations = new ArrayList<>(); if (destName.contains(DESTINATION_SEPARATOR)) { if (getClient().isDestComposite() && (destCount == ...
@Test public void testCreateDestinations_multiple() throws JMSException { Destination[] destinations = jmsClient.createDestinations(2); assertEquals(2, destinations.length); // suffixes should be added assertDestinationNameType(DEFAULT_DEST + ".0", TOPIC_TYPE, asAmqDest(destinations[...
public static Map<String, Object> convert(FormData data) { Map<String, Object> map = new HashMap<>(); for (String key : data) { if (data.get(key).size() == 1) { // If the form data is file, read it as FileItem, else read as String. if (data.getFirst(key).getF...
@Test public void shouldToGetConvertedFormDataInAMapGroupedByKey() { String aKey = "aKey"; String aValue = "aValue"; String anotherValue = "anotherValue"; FormData formData = new FormData(99); formData.add(aKey, aValue); formData.add(aKey, anotherValue); Map...
public static boolean isEmpty( CharSequence val ) { return val == null || val.length() == 0; }
@Test public void testIsEmptyList() { assertTrue( Utils.isEmpty( (List<String>) null ) ); assertTrue( Utils.isEmpty( new ArrayList<String>() ) ); assertFalse( Utils.isEmpty( Arrays.asList( "test", 1 ) ) ); }
@Override public void verify(byte[] data, byte[] signature, MessageDigest digest) { final byte[] decrypted = engine.processBlock(signature, 0, signature.length); final int delta = checkSignature(decrypted, digest); final int offset = decrypted.length - digest.getDigestLength() - delta; ...
@Test public void shouldValidateSignatureSHA1() { final byte[] challenge = CryptoUtils.random(40); final byte[] signature = sign(0x54, challenge, ISOTrailers.TRAILER_SHA1, "SHA1"); new DssRsaSignatureVerifier(PUBLIC).verify(challenge, signature, "SHA1"); }
static boolean isRemoteSegmentWithinLeaderEpochs(RemoteLogSegmentMetadata segmentMetadata, long logEndOffset, NavigableMap<Integer, Long> leaderEpochs) { long segmentEndOffset = segmentMetadata.endOffset();...
@Test public void testRemoteSegmentWithinLeaderEpochs() { // Test whether a remote segment is within the leader epochs final long logEndOffset = 90L; TreeMap<Integer, Long> leaderEpochToStartOffset = new TreeMap<>(); leaderEpochToStartOffset.put(0, 0L); leaderEpochToStartOff...
@Delete(uri = "{namespace}/{id}") @ExecuteOn(TaskExecutors.IO) @Operation(tags = {"Flows"}, summary = "Delete a flow") @ApiResponse(responseCode = "204", description = "On success") public HttpResponse<Void> delete( @Parameter(description = "The flow namespace") @PathVariable String namespace, ...
@Test void deletedFlow() { Flow flow = generateFlow("io.kestra.unittest", "a"); FlowWithSource result = client.toBlocking().retrieve(POST("/api/v1/flows", flow), FlowWithSource.class); assertThat(result.getId(), is(flow.getId())); assertThat(result.getRevision(), is(1)); Ht...
@Override public Object read(final PostgreSQLPacketPayload payload, final int parameterValueLength) { byte[] result = new byte[parameterValueLength]; payload.getByteBuf().readBytes(result); return result; }
@Test void assertRead() { ByteBuf byteBuf = Unpooled.wrappedBuffer("value".getBytes(StandardCharsets.UTF_8)); PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8); assertThat(new PostgreSQLByteaBinaryProtocolValue().read(payload, 5), is("value".getBy...
@Override public OUT nextRecord(OUT record) throws IOException { OUT returnRecord = null; do { returnRecord = super.nextRecord(record); } while (returnRecord == null && !reachedEnd()); return returnRecord; }
@Test void testReadSparseWithNullFieldsForTypes() { try { final String fileContent = "111|x|222|x|333|x|444|x|555|x|666|x|777|x|888|x|999|x|000|x|\n" + "000|x|999|x|888|x|777|x|666|x|555|x|444|x|333|x|222|x|111|x|"; final FileInputSplit...
@Override public void setValue(double value) { _value = value; }
@Test void testSetValue() { AggregationResultHolder resultHolder = new DoubleAggregationResultHolder(DEFAULT_VALUE); for (int i = 0; i < 1000; i++) { double expected = RANDOM.nextDouble(); resultHolder.setValue(expected); double actual = resultHolder.getDoubleResult(); Assert.assertE...
@Override public int hashCode() { JobKey key = getKey(); return key == null ? 0 : getKey().hashCode(); }
@Test public void testHashCode() { JobDetailImpl job = new JobDetailImpl(); Assert.assertThat(job.hashCode(), Matchers.is(0)); job.setName("test"); Assert.assertThat(job.hashCode(), Matchers.not(Matchers.is(0))); job.setGroup("test"); Assert.assertThat(job.hashCode(), Matchers.not(Matchers.is(0))); ...
static <T> T getWildcardMappedObject(final Map<String, T> mapping, final String query) { T value = mapping.get(query); if (value == null) { for (String key : mapping.keySet()) { // Turn the search key into a regex, using all characters but the * as a literal. ...
@Test public void testSubdirExact() throws Exception { // Setup test fixture. final Map<String, Object> haystack = Map.of("myplugin/baz/foo", new Object()); // Execute system under test. final Object result = PluginServlet.getWildcardMappedObject(haystack, "myplugin/baz/foo"); ...
@Override public void onClick(View v) { switch (v.getId()) { case R.id.quick_keys_popup_close: mKeyboardActionListener.onKey(KeyCodes.CANCEL, null, 0, null, true); break; case R.id.quick_keys_popup_backspace: mKeyboardActionListener.onKey(KeyCodes.DELETE, null, 0, null, true); ...
@Test public void testOnClickBackSpace() throws Exception { OnKeyboardActionListener keyboardActionListener = Mockito.mock(OnKeyboardActionListener.class); FrameKeyboardViewClickListener listener = new FrameKeyboardViewClickListener(keyboardActionListener); Mockito.verifyZeroInteractions(keyboardA...
@Override public SqlRequest refactor(QueryParamEntity entity, Object... args) { if (injector == null) { initInjector(); } return injector.refactor(entity, args); }
@Test void testJoin() { QueryAnalyzerImpl analyzer = new QueryAnalyzerImpl( database, "select *,t2.c from s_test t " + "left join (select z.id id, count(1) c from s_test z) t2 on t2.id = t.id"); SqlRequest request = analyzer .refactor(QueryParamEn...
@Override public ListConsumerGroupOffsetsResult listConsumerGroupOffsets(Map<String, ListConsumerGroupOffsetsSpec> groupSpecs, ListConsumerGroupOffsetsOptions options) { SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, OffsetAndMetad...
@Test public void testListConsumerGroupOffsets() throws Exception { try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); // Retriable FindCoordinatorResponse errors should be retried ...
@Override public int choosePartition(Message<?> msg, TopicMetadata topicMetadata) { // If the message has a key, it supersedes the round robin routing policy if (msg.hasKey()) { return signSafeMod(hash.makeHash(msg.getKey()), topicMetadata.numPartitions()); } if (isBatch...
@Test public void testBatchingAwareness() throws Exception { Message<?> msg = mock(Message.class); when(msg.getKey()).thenReturn(null); Clock clock = mock(Clock.class); RoundRobinPartitionMessageRouterImpl router = new RoundRobinPartitionMessageRouterImpl( HashingSc...
@SuppressWarnings("OptionalGetWithoutIsPresent") public StatementExecutorResponse execute( final ConfiguredStatement<DescribeConnector> configuredStatement, final SessionProperties sessionProperties, final KsqlExecutionContext ksqlExecutionContext, final ServiceContext serviceContext ) { ...
@Test public void shouldDescribeKnownConnectorIfTopicListFails() { // Given: when(connectClient.topics("connector")).thenReturn(ConnectResponse.failure( "Topic tracking is disabled.", HttpStatus.SC_FORBIDDEN)); // When: final Optional<KsqlEntity> entity = executor .execute(describeSta...
@Override public SingleRuleConfiguration swapToObject(final YamlSingleRuleConfiguration yamlConfig) { SingleRuleConfiguration result = new SingleRuleConfiguration(); if (null != yamlConfig.getTables()) { result.getTables().addAll(yamlConfig.getTables()); } result.setDefau...
@Test void assertSwapToObjectWithoutDataSource() { assertFalse(new YamlSingleRuleConfigurationSwapper().swapToObject(new YamlSingleRuleConfiguration()).getDefaultDataSource().isPresent()); }
@Override public void writePendingBytes() throws Http2Exception { monitor.writePendingBytes(); }
@Test public void payloadSmallerThanWindowShouldBeWrittenImmediately() throws Http2Exception { FakeFlowControlled data = new FakeFlowControlled(5); sendData(STREAM_A, data); data.assertNotWritten(); verifyZeroInteractions(listener); controller.writePendingBytes(); dat...
public boolean isDisabled() { return _disabled; }
@Test public void withSomeData() throws JsonProcessingException { String confStr = "{\n" + " \"version\": 42\n" + "}"; IndexConfig config = JsonUtils.stringToObject(confStr, IndexConfig.class); assertFalse(config.isDisabled(), "Unexpected disabled"); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { JsonNode jsonNode = JacksonUtil.toJsonNode(msg.getData()); if (jsonNode.isArray()) { ArrayNode data = (ArrayNode) jsonNode; if (data.isEmpty()) { ...
@Test void givenNoArrayMsg_whenOnMsg_thenFailure() throws Exception { String data = "{\"Attribute_1\":22.5,\"Attribute_2\":10.3}"; JsonNode dataNode = JacksonUtil.toJsonNode(data); TbMsg msg = getTbMsg(deviceId, dataNode.toString()); node.onMsg(ctx, msg); ArgumentCaptor<TbMs...
public Future<Void> executeFailed(ProcessingContext<T> context, Stage stage, Class<?> executingClass, Throwable error) { markAsFailed(); context.currentContext(stage, executingClass); context.error(error); errorHandlingMetrics.recordFailure(); Future<Void> errantRecordFuture = re...
@Test public void testExecuteFailed() { RetryWithToleranceOperator<ConsumerRecord<byte[], byte[]>> retryWithToleranceOperator = genericOperator(0, ALL, errorHandlingMetrics); ProcessingContext<ConsumerRecord<byte[], byte[]>> context = new ProcessingContext<>(consumerRecord); retryWithTolera...
public int run(String... argv) { if (argv.length == 0) { printUsage(); return -1; } // Sanity check on the number of arguments String cmd = argv[0]; Command command = mCommands.get(cmd); if (command == null) { String[] replacementCmd = getReplacementCmd(cmd); if (replac...
@Test public void commandExists() throws Exception { TestShell shell = new TestShell(); assertEquals(0, shell.run("cmd")); }
@Override public ApiResult<CoordinatorKey, TransactionDescription> handleResponse( Node broker, Set<CoordinatorKey> keys, AbstractResponse abstractResponse ) { DescribeTransactionsResponse response = (DescribeTransactionsResponse) abstractResponse; Map<CoordinatorKey, Tra...
@Test public void testHandleSuccessfulResponse() { String transactionalId1 = "foo"; String transactionalId2 = "bar"; Set<String> transactionalIds = mkSet(transactionalId1, transactionalId2); DescribeTransactionsHandler handler = new DescribeTransactionsHandler(logContext); ...
@Override protected ExecuteContext doBefore(ExecuteContext context) { final Object object = context.getObject(); if (object instanceof HandlerExecutionChain) { HandlerExecutionChain chain = (HandlerExecutionChain) object; chain.addInterceptor(getInterceptor()); } ...
@Test public void testAddInterceptor() { final HandlerExecutionChain chain = new HandlerExecutionChain(new Object()); final ExecuteContext executeContext = ExecuteContext.forMemberMethod(chain, null, null, null, null); final SpringWebHandlerInterceptor springWebHandlerInterceptor = new Sprin...
public static File unzip(String zipFilePath) throws UtilException { return unzip(zipFilePath, DEFAULT_CHARSET); }
@Test @Disabled public void sizeUnzipTest() throws IOException { final String zipPath = "e:\\hutool\\demo.zip"; final String outPath = "e:\\hutool\\test"; final ZipFile zipFile = new ZipFile(zipPath, Charset.forName("GBK")); final File file = new File(outPath); // 限制解压文件大小为637KB final long size = 637*1024...
@Override public final String toString() { return toURI().toString(); }
@Test public void testToString() throws IOException { String parentFolder = "parentFolder"; File parentFile = tmp.newFolder(parentFolder); String child = "child"; File childFile = new File(parentFile, child); VirtualFile vf = new VirtualFileMinimalImplementation(childFile); ...
@Schema(description = "응답 메시지", example = """ data: { "aDomain": { // 단수명사는 object 형태로 반환 ... },` "bDomains": [ // 복수명사는 array 형태로 반환 ... ] } """) private T data; @Builder...
@Test @DisplayName("SuccessResponse.from() - data가 존재하는 성공 응답") public void successResponseWithData() { // Given String key = "example"; String value = "data"; // When SuccessResponse<?> response = SuccessResponse.from(key, value); // Then assertEquals("...
public static double of(int[] truth, int[] prediction) { if (truth.length != prediction.length) { throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, prediction.length)); } ConfusionMatrix confusion = ConfusionMatrix.of(truth, pr...
@Test public void test0(){ System.out.println("numerator = 0"); int[] truth = {0, 0, 0, 0, 1, 1, 1, 1}; int[] prediction = {0, 1, 0, 1, 0, 1, 0, 1}; double expResult = 0; double result = MatthewsCorrelation.of(truth, prediction); assertEquals(expResult, result, 1E-5)...
public List<? extends IAvroInputField> getDefaultFields() throws Exception { ArrayList<AvroInputField> fields = new ArrayList<>(); Schema avroSchema = readAvroSchema(); for ( Schema.Field f : avroSchema.getFields() ) { AvroSpec.DataType actualAvroType = findActualDataType( f ); AvroSpec.DataTyp...
@Test public void testGetDefaultFields() throws Exception { PentahoAvroInputFormat format = Mockito.spy( new PentahoAvroInputFormat( ) ); Schema.Parser parser = new Schema.Parser(); Schema schema = parser.parse( new File( getFilePath( TYPES_SCHEMA_AVRO ) ) ); doReturn( schema ).when( format ).readAvro...
@Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { // 1.1 参数校验 if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } ...
@Test public void testImportUserList_01() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setEmail(randomEmail()); o.setMobile(randomMobile()); }); // mock 方法,模拟失败 doThrow(new ServiceException(DEPT_NOT_FOUND)).when...
@Override public Num getValue(int index) { return delegate.getValue(index); }
@Test public void getValue() { final NumericIndicator numericIndicator = NumericIndicator.of(cp1); for (int i = 0; i < series.getBarCount(); i++) { assertNumEquals(cp1.getValue(i), numericIndicator.getValue(i)); } }
@Override public void clear() { throw MODIFICATION_ATTEMPT_ERROR; }
@Test void testClear() throws Exception { long value = reduceState.get(); assertThat(value).isEqualTo(42L); assertThatThrownBy(() -> reduceState.clear()) .isInstanceOf(UnsupportedOperationException.class); }
public static void i(String tag, String message, Object... args) { sLogger.i(tag, message, args); }
@Test public void info() { String tag = "TestTag"; String message = "Test message"; LogManager.i(tag, message); verify(logger).i(tag, message); }
@Override public String toString() { if (mUriString != null) { return mUriString; } StringBuilder sb = new StringBuilder(); if (mUri.getScheme() != null) { sb.append(mUri.getScheme()); sb.append("://"); } if (hasAuthority()) { if (mUri.getScheme() == null) { sb....
@Test public void normalizeWindowsTests() { assumeTrue(WINDOWS); assertEquals("c:/a/b", new AlluxioURI("c:\\a\\b").toString()); assertEquals("c:/a/c", new AlluxioURI("c:\\a\\b\\..\\c").toString()); }
public boolean hasOnlineDir(int brokerId, Uuid directoryId) { BrokerRegistration registration = registration(brokerId); return registration != null && registration.hasOnlineDir(directoryId); }
@Test public void testHasOnlineDir() { ClusterControlManager clusterControl = new ClusterControlManager.Builder(). setClusterId("pjvUwj3ZTEeSVQmUiH3IJw"). setFeatureControlManager(new FeatureControlManager.Builder().build()). setBrokerUncleanShutdownHandler((b...
public IterableOfProtosUsingCorrespondence<M> displayingDiffsPairedBy( Function<? super M, ?> keyFunction) { return usingCorrespondence().displayingDiffsPairedBy(keyFunction); }
@Test public void testDisplayingDiffsPairedBy() { Message actualInt3 = parse("o_int: 3 r_string: 'foo'"); Message actualInt4 = parse("o_int: 4 r_string: 'bar'"); Message expectedInt3 = parse("o_int: 3 r_string: 'baz'"); Message expectedInt4 = parse("o_int: 4 r_string: 'qux'"); Function<Message, I...
protected static VplsOperation getOptimizedVplsOperation(Deque<VplsOperation> operations) { if (operations.isEmpty()) { return null; } // no need to optimize if the queue contains only one operation if (operations.size() == 1) { return operations.getFirst(); ...
@Test public void testOptimizeOperationsRToU() { Deque<VplsOperation> operations = new ArrayDeque<>(); VplsData vplsData = VplsData.of(VPLS1); vplsData.addInterfaces(ImmutableSet.of(V100H1)); VplsOperation vplsOperation = VplsOperation.of(vplsData, ...
public boolean addAll(final Collection<? extends Integer> coll) { boolean added = false; for (final Integer value : coll) { added |= add(value); } return added; }
@Test void addingEmptySetDoesNothing() { addTwoElements(testSet); assertFalse(testSet.addAll(new IntHashSet(100))); assertFalse(testSet.addAll(new HashSet<>())); assertContainsElements(testSet); }
@Override public T setTimeMillis(K name, long value) { throw new UnsupportedOperationException("read only"); }
@Test public void testSetTimeMillis() { assertThrows(UnsupportedOperationException.class, new Executable() { @Override public void execute() { HEADERS.setTimeMillis("name", 0); } }); }
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("match") String match) { if ( string == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "string", "cannot be null" ) ); } if ( match == null ) { ret...
@Test void invokeMatchExists() { FunctionTestUtil.assertResult(substringBeforeFunction.invoke("foobar", "ob"), "fo"); FunctionTestUtil.assertResult(substringBeforeFunction.invoke("foobar", "o"), "f"); }
@Override public CompletableFuture<SubscriptionData> querySubscriptionByConsumer(String address, QuerySubscriptionByConsumerRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<SubscriptionData> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.cre...
@Test public void assertQuerySubscriptionByConsumerWithSuccess() throws Exception { SubscriptionData responseBody = new SubscriptionData(); setResponseSuccess(RemotingSerializable.encode(responseBody)); QuerySubscriptionByConsumerRequestHeader requestHeader = mock(QuerySubscriptionByConsumer...
public static <T> T newInstanceOrNull(Class<? extends T> clazz, Object... params) { Constructor<T> constructor = selectMatchingConstructor(clazz, params); if (constructor == null) { return null; } try { return constructor.newInstance(params); } catch (Ill...
@Test public void newInstanceOrNull_noMatchingConstructorFound_different_length() { ClassWithNonArgConstructor instance = InstantiationUtils.newInstanceOrNull(ClassWithNonArgConstructor.class, "foo"); assertNull(instance); }