focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public long getConnectTimeout() { return safelyParseLongValue(CONNECT_TIMEOUT_PROPERTY).orElse(DEFAULT_TIMEOUT); }
@Test public void getConnectTimeout_returns_value_of_property() { long expected = new Random().nextInt(9_456_789); settings.setProperty("sonar.alm.timeout.connect", expected); assertThat(underTest.getConnectTimeout()).isEqualTo(expected); }
public PluggableArtifactConfig findByArtifactId(String artifactId) { for (PluggableArtifactConfig artifact : getPluggableArtifactConfigs()) { if (artifact.getId().equals(artifactId)) { return artifact; } } return null; }
@Test public void findByArtifactId_shouldReturnNullWhenPluggableArtifactConfigNotExistWithGivenId() { ArtifactTypeConfigs allConfigs = new ArtifactTypeConfigs(); allConfigs.add(new PluggableArtifactConfig("s3", "cd.go.s3")); allConfigs.add(new PluggableArtifactConfig("docker", "cd.go.docker"...
@Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && isApplicableType(field)) { final Class<? extends Annotation> patternClass = ruleFa...
@Test public void testRegex() { when(config.isIncludeJsr303Annotations()).thenReturn(true); final String patternValue = "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"; when(node.asText()).thenReturn(patternValue); when(fieldVar.annotate(patternClass)...
final void ensureAvailable(int len) { if (available() < len) { if (buffer != null) { int newCap = Math.max(Math.max(buffer.length << 1, buffer.length + len), firstGrowthSize); buffer = Arrays.copyOf(buffer, newCap); } else { buffer = new by...
@Test public void testEnsureAvailable_smallLen() { out.buffer = null; out.ensureAvailable(1); assertEquals(10, out.buffer.length); }
@Override public ShenyuContext decorator(final ShenyuContext shenyuContext, final MetaData metaData) { String path = shenyuContext.getPath(); shenyuContext.setMethod(path); shenyuContext.setRealUrl(path); shenyuContext.setRpcType(RpcTypeEnum.HTTP.getName()); shenyuContext.set...
@Test public void decoratorTest() { MetaData metaData = new MetaData(); ShenyuContext shenyuContext = new ShenyuContext(); shenyuContext.setPath(MOCK_CONTEXT_PATH); shenyuContext.setHttpMethod(MOCK_CONTEXT_PATH); ShenyuContext decorator = divideShenyuContextDecorator.decorato...
public static void closeAllQuietly(Collection<? extends AutoCloseable> collection) { if (collection == null) { return; } for (AutoCloseable closeable : collection) { closeQuietly(closeable); } }
@Test public void test_closeAllQuietly_whenNullCollection() { closeAllQuietly(null); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testParseNewStyleResourceWithCustomResourceMemoryNegative() throws Exception { expectNegativeValueOfResource("memory"); parseResourceConfigValue("vcores=2,memory-mb=-5120,test1=4"); }
public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim(); try { return Integer.parseInt(value); } catch (Exception e) { // Ignore } logger.warn( ...
@Test public void getIntDefaultValueWithPropertValueIsNotInt() { System.setProperty("key", "NotInt"); assertEquals(1, SystemPropertyUtil.getInt("key", 1)); }
public static void addConfigsToProperties( Properties props, Map<String, String> commonConf, Map<String, String> clientConf) { for (Map.Entry<String, String> commonEntry : commonConf.entrySet()) { props.setProperty(commonEntry.getKey(), commonEntry.getValue()); } for (Map.Ent...
@Test public void testClientConfigOverwritesBothDefaultAndCommonConfigs() { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.ACKS_CONFIG, "all"); Properties resultProps = new Properties(); res...
@Override protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { final NSDictionary serialized = NSDictionary.dictionaryWithContentsOfFile(file.getAbsolute()); if(null == serialized) { throw new LocalAccessDeniedException(String.format("Inv...
@Test(expected = AccessDeniedException.class) public void testParseNotFound() throws Exception { new CloudMounterBookmarkCollection().parse(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f")); }
@Override public YamlSingleRuleConfiguration swapToYamlConfiguration(final SingleRuleConfiguration data) { YamlSingleRuleConfiguration result = new YamlSingleRuleConfiguration(); result.getTables().addAll(data.getTables()); data.getDefaultDataSource().ifPresent(result::setDefaultDataSource);...
@Test void assertSwapToYamlWithoutDataSource() { assertNull(new YamlSingleRuleConfigurationSwapper().swapToYamlConfiguration(new SingleRuleConfiguration()).getDefaultDataSource()); }
public static Optional<ParsedMetricName> parseMetricName(String metricName) { if (metricName.isEmpty()) { return Optional.empty(); } List<String> metricNameSplit = Splitter.on(METRIC_NAME_DELIMITER).limit(2).splitToList(metricName); if (metricNameSplit.size() == 0 || metricNameSplit.get(...
@Test public void testParseMetricName_noLabels() { String baseMetricName = "baseMetricName"; LabeledMetricNameUtils.MetricNameBuilder builder = LabeledMetricNameUtils.MetricNameBuilder.baseNameBuilder(baseMetricName); String metricName = builder.build("namespace").getName(); Optional<LabeledMe...
public static String generateToken(final String userName, final String key, final String clientId) { return generateToken(userName, key, clientId, null); }
@Test public void testGenerateToken() { String token = JwtUtils.generateToken("userName", KEY, "clientId"); assertThat(token, notNullValue()); assertThat(JwtUtils.getIssuer(token), is("userName")); assertThat(JwtUtils.getClientId(token), is("clientId")); }
@Override public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) { Collection<Stri...
@Test void assertDecideWhenAllTablesIsNotBindingTablesAndContainsPagination() { SelectStatementContext select = createStatementContext(); when(select.isContainsJoinQuery()).thenReturn(true); when(select.getPaginationContext().isHasPagination()).thenReturn(true); ShardingRule sharding...
public Mono<Void> createProducerAcl(KafkaCluster cluster, CreateProducerAclDTO request) { return adminClientService.get(cluster) .flatMap(ac -> createAclsWithLogging(ac, createProducerBindings(request))) .then(); }
@Test void createsProducerDependantAclsWhenTopicsAndTxIdSpecifiedByPrefix() { ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class); when(adminClientMock.createAcls(createdCaptor.capture())) .thenReturn(Mono.empty()); var principal = UUID.randomUUID().to...
public static int getAssuranceLevel(String key) throws SamlSessionException { if (!numberMap.containsKey(key)) { throw new SamlSessionException("Assurance level not found"); } return numberMap.get(key); }
@Test void invalidAssuranceLevelName() { SamlSessionException exception = assertThrows(SamlSessionException.class, () -> LevelOfAssurance.getAssuranceLevel("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS")); assertEquals("Assurance level not found", exception.getMessage()); }
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 shouldParseFloatType() { byte[] value = new byte[] {64, 0, 0, 0}; assertEquals(2.0f, (Float) PARSER.getCellValue(cell(value), FLOAT), 0.001); }
@Override public int read() { if (nextChar == UNSET || nextChar >= buf.length) { fill(); if (nextChar == UNSET) { return END_OF_STREAM; } } byte signedByte = buf[nextChar]; nextChar++; return signedByte & 0xFF; }
@Test void read_from_ClosableIterator_with_single_line() throws IOException { assertThat(read(create("line1"))).isEqualTo("line1"); }
public static <InputT, OutputT> MapElements<InputT, OutputT> via( final InferableFunction<InputT, OutputT> fn) { return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor()); }
@Test public void testSimpleFunctionClassDisplayData() { SimpleFunction<?, ?> simpleFn = new SimpleFunction<Integer, Integer>() { @Override public Integer apply(Integer input) { return input; } }; MapElements<?, ?> simpleMap = MapElements.via(simpleFn...
public Shader add(int type, String name) { units.add(new Unit(type, name)); return this; }
@Test public void testShaders() throws Exception { String verifier = System.getProperty("glslang.path"); Assume.assumeFalse("glslang.path is not set", Strings.isNullOrEmpty(verifier)); Template[] templates = { new Template() .addInclude(GpuPlugin.class) .add(key -> { if ("version_header".equa...
public static ProxyBackendHandler newInstance(final SQLStatement sqlStatement, final ConnectionSession connectionSession) { return createBackendHandler(sqlStatement, connectionSession); }
@Test void assertDatabaseOperateBackendHandlerFactoryThrowUnsupportedOperationException() { assertThrows(UnsupportedSQLOperationException.class, () -> DatabaseOperateBackendHandlerFactory.newInstance(mock(AlterDatabaseStatement.class), mock(ConnectionSession.class))); }
public Optional<Session> login(@Nullable String currentSessionId, String host, ActorAwareAuthenticationToken authToken) throws AuthenticationServiceUnavailableException { final String previousSessionId = StringUtils.defaultIfBlank(currentSessionId, null); final Subjec...
@Test public void validAuthToken() { setUpUserMock(); assertFalse(SecurityUtils.getSubject().isAuthenticated()); Optional<Session> session = sessionCreator.login(null, "host", validToken); assertTrue(session.isPresent()); assertEquals(SESSION_TIMEOUT, session.get().getTimeou...
@VisibleForTesting public ConfigDO validateConfigExists(Long id) { if (id == null) { return null; } ConfigDO config = configMapper.selectById(id); if (config == null) { throw exception(CONFIG_NOT_EXISTS); } return config; }
@Test public void testValidateConfigExists_success() { // mock 数据 ConfigDO dbConfigDO = randomConfigDO(); configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据 // 调用成功 configService.validateConfigExists(dbConfigDO.getId()); }
@Override public void execute(SensorContext context) { Set<String> reportPaths = loadReportPaths(); Map<String, SarifImportResults> filePathToImportResults = new HashMap<>(); for (String reportPath : reportPaths) { try { SarifImportResults sarifImportResults = processReport(context, reportP...
@Test public void execute_whenDeserializationThrowsMessageException_shouldRethrow() throws NoSuchFileException { sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1); NoSuchFileException e = new NoSuchFileException("non-existent"); failDeserializingReportWithException(FILE_1, e); SarifIssues...
@VisibleForTesting CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) { if (pushNotification.tokenType() == PushNotification.TokenType.APN && !pushNotification.urgent()) { // APNs imposes a per-device limit on background push notifications; sche...
@Test void testSendNotificationUnregisteredApn() { final Account account = mock(Account.class); final Device device = mock(Device.class); final UUID aci = UUID.randomUUID(); when(device.getId()).thenReturn(Device.PRIMARY_ID); when(device.getApnId()).thenReturn("apns-token"); when(device.getVoi...
@Nonnull @Override public Optional<? extends INode> parse( @Nullable final String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } for (IMapper mapper : jcaSpecificAlgorithmMappers) { Optional<? extend...
@Test void keyAgreement() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaAlgorithmMapper jcaAlgorithmMapper = new JcaAlgorithmMapper(); Optional<? extends INode> assetOptional = jcaAlgorit...
public FEELFnResult<Boolean> invoke(@ParameterName("range1") Range range1, @ParameterName("range2") Range range2) { if (range1 == null) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "range1", "cannot be null")); } if (range2 == null) { return FE...
@Test void invokeParamRangeAndRange() { FunctionTestUtil.assertResult( overlapsFunction.invoke( new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ), new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ), ...
@Override public ExecuteContext onThrow(ExecuteContext context) { ThreadLocalUtils.removeRequestData(); return context; }
@Test public void testOnThrow() { ThreadLocalUtils.setRequestData(new RequestData(null, "", "")); interceptor.onThrow(context); Assert.assertNull(ThreadLocalUtils.getRequestData()); }
public ProviderBuilder charset(String charset) { this.charset = charset; return getThis(); }
@Test void charset() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.charset("utf-8"); Assertions.assertEquals("utf-8", builder.build().getCharset()); }
public RingbufferConfig setBackupCount(int backupCount) { this.backupCount = checkBackupCount(backupCount, asyncBackupCount); return this; }
@Test public void setBackupCount() { RingbufferConfig config = new RingbufferConfig(NAME); config.setBackupCount(4); assertEquals(4, config.getBackupCount()); }
@Override public boolean checkAccess(UserGroupInformation callerUGI, JobACL jobOperation) { AccessControlList jobACL = jobACLs.get(jobOperation); if (jobACL == null) { return true; } return aclsManager.checkAccess(callerUGI, jobOperation, userName, jobACL); }
@Test public void testCheckAccess() { // Create two unique users String user1 = System.getProperty("user.name"); String user2 = user1 + "1234"; UserGroupInformation ugi1 = UserGroupInformation.createRemoteUser(user1); UserGroupInformation ugi2 = UserGroupInformation.createRemoteUser(user2); /...
public static List<TriStateSelection> forAgentsResources(Set<ResourceConfig> resourceConfigs, Agents agents) { return convert(resourceConfigs, agents, new Assigner<>() { @Override public boolean shouldAssociate(Agent agent, ResourceConfig resourceConfig) { return agent.ge...
@Test public void shouldHaveActionRemoveIfThereAreNoAgents() { List<TriStateSelection> selections = TriStateSelection.forAgentsResources(resourceConfigs, agents); assertThat(selections, hasItem(new TriStateSelection("one", TriStateSelection.Action.remove))); assertThat(selections, hasItem(ne...
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } checkNoComponentAnnotations(stepClass); if (hasCucumberContextConfiguration(stepClass)) { checkOnlyOneClassHasCucumberContextConfiguration(step...
@Test void shouldNotFailWithCucumberContextConfigurationInheritedAnnotation() { final ObjectFactory factory = new SpringFactory(); factory.addClass(WithInheritedAnnotation.class); assertDoesNotThrow(factory::start); }
public List<ContainerLogMeta> collect( LogAggregationFileController fileController) throws IOException { List<ContainerLogMeta> containersLogMeta = new ArrayList<>(); RemoteIterator<FileStatus> appDirs = fileController. getApplicationDirectoriesOfUser(logsRequest.getUser()); while (appDirs.ha...
@Test void testMultipleFileBetweenSize() throws IOException { ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder request = new ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder(); Set<String> fileSizeExpressions = new HashSet<>(); fileSizeExpressions.add(">50"); fileSizeExpressions.add("<...
public static String getPartitionColumn(TableConfig tableConfig) { // check InstanceAssignmentConfigMap is null or empty, if (!MapUtils.isEmpty(tableConfig.getInstanceAssignmentConfigMap())) { for (InstanceAssignmentConfig instanceAssignmentConfig : tableConfig.getInstanceAssignmentConfigMap().values()) {...
@Test public void testGetPartitionColumnWithReplicaGroupConfig() { ReplicaGroupStrategyConfig replicaGroupStrategyConfig = new ReplicaGroupStrategyConfig(PARTITION_COLUMN, 1); TableConfig tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(TABLE_NAME).build(); // setting...
@Override public PageResult<RoleDO> getRolePage(RolePageReqVO reqVO) { return roleMapper.selectPage(reqVO); }
@Test public void testGetRolePage() { // mock 数据 RoleDO dbRole = randomPojo(RoleDO.class, o -> { // 等会查询到 o.setName("土豆"); o.setCode("tudou"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCreateTime(buildTime(2022, 2, 8)); }); ...
public static String getFileName(String application) { return "JavaMelody_" + application.replace(' ', '_').replace("/", "") + '_' + I18N.getCurrentDate().replace('/', '_') + ".pdf"; }
@Test public void testGetFileName() { assertNotNull("filename", PdfReport.getFileName("test")); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testLeaderEpochInConsumerRecord() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); int partitionLeaderEpoch = 1; ByteBuffer buffer = ByteBuffer.allocate(1024); MemoryRecordsBuilder builder = MemoryRecords.builder(buffe...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 2) { onInvalidDataReceived(device, data); return; } // Read the Op Code final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); // Estima...
@Test public void onContinuousGlucoseCalibrationValueReceived_withCrc() { final MutableData data = new MutableData(new byte[13]); data.setValue(6, Data.FORMAT_UINT8, 0); data.setValue(1, 2, Data.FORMAT_SFLOAT, 1); data.setValue(10, Data.FORMAT_UINT16_LE, 3); data.setValue(0x32, Data.FORMAT_UINT8, 5); data....
public void setContract(@Nullable Produce contract) { this.contract = contract; setStoredContract(contract); handleContractState(); }
@Test public void cabbageContractOnionHarvestableAndCabbageGrowing() { final long unixNow = Instant.now().getEpochSecond(); final long expectedTime = unixNow + 60; // Get the two allotment patches final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773); final FarmingPatch patch2 = farming...
public static String truncate(String string, int maxLength) { return truncate(string, maxLength, n -> "...[truncated " + n + " symbols]"); }
@Test void testTruncate() { int maxLength = 5; assertThat(StringUtils.truncate(null, maxLength)).isNull(); assertThat(StringUtils.truncate("", maxLength)).isEmpty(); assertThat(StringUtils.truncate("123", maxLength)).isEqualTo("123"); assertThat(StringUtils.truncate("1234567"...
@Override public void afterCommitted(TransactionState txnState, boolean txnOperated) throws UserException { long taskBeId = -1L; try { if (txnOperated) { // find task in job Optional<RoutineLoadTaskInfo> routineLoadTaskInfoOptional = routineLoadTaskInfoLis...
@Test public void testAfterCommitted(@Mocked RoutineLoadMgr routineLoadMgr, @Injectable TransactionState transactionState, @Injectable KafkaTaskInfo routineLoadTaskInfo) throws UserException { Deencapsulation.setField(routineLoadTaskInfo, "ro...
@Override public boolean validateTree(ValidationContext validationContext) { validate(validationContext); return !hasErrors(); }
@Test public void validateTree_shouldValidateNullId() { PluggableArtifactConfig artifactConfig = new PluggableArtifactConfig(null, "s3"); final ArtifactStores artifactStores = new ArtifactStores(new ArtifactStore("s3", "cd.go.s3")); final boolean result = artifactConfig.validateTree(Validat...
@Override public boolean shouldWait() { RingbufferContainer ringbuffer = getRingBufferContainerOrNull(); if (ringbuffer == null) { return true; } if (ringbuffer.isTooLargeSequence(sequence) || ringbuffer.isStaleSequence(sequence)) { //no need to wait, let the ...
@Test public void whenOnTailAndBufferEmpty() { ReadOneOperation op = getReadOneOperation(ringbuffer.tailSequence()); // since there is an item, we don't need to wait op.shouldWait(); assertThrows(StaleSequenceException.class, op::beforeRun); }
@Override protected Map<String, GroupInfo> createGroupInfos() { AbstractSeriesSelector seriesSelector = new AbstractSeriesSelector() { @Override public Iterable<String> select(Sample sample) { return Collections.singletonList(sampleVariableName); } ...
@Test public void testCreateGroupInfos() { // Testing defaults values assertThat(map.containsKey("Generic group"), equalTo(true)); assertThat(map.containsKey("foo"), equalTo(false)); assertThat(map.get("Generic group").getAggregatorFactory().getClass(), equalTo(org.ap...
public static String capitalize(String string) { return string == null ? null : string.substring( 0, 1 ).toUpperCase( Locale.ROOT ) + string.substring( 1 ); }
@Test public void testCapitalize() { assertThat( Strings.capitalize( null ) ).isNull(); assertThat( Strings.capitalize( "c" ) ).isEqualTo( "C" ); assertThat( Strings.capitalize( "capitalize" ) ).isEqualTo( "Capitalize" ); assertThat( Strings.capitalize( "AlreadyCapitalized" ) ).isEqu...
@Override public int run(String[] args) throws Exception { try { webServiceClient = WebServiceClient.getWebServiceClient().createClient(); return runCommand(args); } finally { if (yarnClient != null) { yarnClient.close(); } if (webServiceClient != null) { webServi...
@Test (timeout = 5000) public void testWithNonMatchingEntityIds() throws Exception { ApplicationId appId1 = ApplicationId.newInstance(0, 1); ApplicationId appId2 = ApplicationId.newInstance(0, 2); ApplicationAttemptId appAttemptId1 = ApplicationAttemptId.newInstance(appId1, 1); Application...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final DownloadBuilder builder = new DbxUserFilesRequests(session.getClient(file)) .downloadBuilder(containerService.getKey(fil...
@Test public void testReadInterrupt() throws Exception { final DropboxWriteFeature write = new DropboxWriteFeature(session); final TransferStatus writeStatus = new TransferStatus(); final byte[] content = RandomUtils.nextBytes(66800); writeStatus.setLength(content.length); fi...
@Override public byte[] echo(byte[] message) { return read(null, ByteArrayCodec.INSTANCE, ECHO, message); }
@Test public void testEcho() { assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes()); }
public Set<Long> calculateUsers(DelegateExecution execution, int level) { Assert.isTrue(level > 0, "level 必须大于 0"); // 获得发起人 ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId()); Long startUserId = NumberUtils.parseLong(processInst...
@Test public void testCalculateUsers_noParentDept() { // 准备参数 DelegateExecution execution = mockDelegateExecution(1L); // mock 方法(startUser) AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L)); when(adminUserApi.getUser(eq(1L))).thenReturn(s...
@Nonnull public TypeSerializer<T> getSerializer() { return typeSerializer.duplicate(); }
@Test void testSerializerDuplication() { // we need a serializer that actually duplicates for testing (a stateful one) // we use Kryo here, because it meets these conditions TestStateDescriptor<String> descr = new TestStateDescriptor<>("foobar", new GenericTypeInfo<>(String.c...
public List<Entry> entries() { return entriesCache; }
@Test void shouldCreateNewIndex() { try (RecordingLog recordingLog = new RecordingLog(tempDir, true)) { assertEquals(0, recordingLog.entries().size()); } }
public synchronized long nextGtid() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { timestamp = lastTimestamp; } if (lastTimestamp == timestamp) { sequence = (sequence + 1) & MAX_SEQUENCE; if (sequence == 0) { timestamp...
@Test public void testClusterIdInGtid() { long gtid = gtidGenerator.nextGtid(); long clusterId = (gtid >> GtidGenerator.CLUSTER_ID_SHIFT) & GtidGenerator.MAX_CLUSTER_ID; Assertions.assertEquals(GtidGenerator.CLUSTER_ID, clusterId, "Cluster ID should be correctly set in GTID"); }
public final static boolean isEnd(String commandPart) { return commandPart.length() == 1 && commandPart.charAt(0) == 'e'; }
@Test public void testEnd() { assertTrue(Protocol.isEnd("e")); assertFalse(Protocol.isEnd("")); assertFalse(Protocol.isEnd("btrue")); try { Protocol.isEnd(null); fail(); } catch (NullPointerException e) { assertTrue(true); } }
@Override public void setValue(Object value, Object elContext) { expression.setValue(elContext, value); }
@Test void testSetValue() { ExpressionParser parser = new SpelExpressionParser(); String expression = "name"; SpringELExpressionObject springELExpressionObject = new SpringELExpressionObject(); Expression defaultExpression = parser.parseExpression(expression); SpringELExpress...
public static void validateRequestHeadersAndUpdateResourceContext(final Map<String, String> headers, final Set<String> customMimeTypesSupported, ServerResourceContext resourceContext) ...
@Test() public void testValidateRequestHeadersForInProcessRequest() throws Exception { Map<String, String> headers = new AbstractMap<String, String>() { @Override public Set<Entry<String, String>> entrySet() { throw new IllegalStateException("Didn't expect headers to be accessed."); ...
public static int getIndexCharsCount( int MaxIndex ) { // int CharsCount = 1; // if ( MaxIndex <= 0 ) return 1; // CharsCount = (int)Math.log10( MaxIndex ) + 1; // return CharsCount; }
@Test public void testgetIndexCharsCount() throws Exception { // assertEquals( 1, BTools.getIndexCharsCount( -5 ) ); assertEquals( 1, BTools.getIndexCharsCount( 5 ) ); assertEquals( 3, BTools.getIndexCharsCount( 345 ) ); // }
TopicPartition renameTopicPartition(TopicPartition upstreamTopicPartition) { if (targetClusterAlias.equals(replicationPolicy.topicSource(upstreamTopicPartition.topic()))) { // this topic came from the target cluster, so we rename like us-west.topic1 -> topic1 return new TopicPartition(re...
@Test public void testDownstreamTopicRenaming() { MirrorCheckpointTask mirrorCheckpointTask = new MirrorCheckpointTask("source1", "target2", new DefaultReplicationPolicy(), null, Collections.emptySet(), Collections.emptyMap(), new CheckpointStore(Collections.emptyMap())); ass...
public static Object removeClass(final Object object) { if (object instanceof Map) { Map<?, ?> map = (Map<?, ?>) object; Object result = map.get("result"); if (result instanceof Map) { Map<?, ?> resultMap = (Map<?, ?>) result; resultMap.remove(...
@Test public void removeClass() { Map<String, Map<String, String>> testMap = new HashMap<>(); Map<String, String> testSubMap = new HashMap<>(); testSubMap.put("class", "NullPointerException.class"); testSubMap.put("not_class", "ClassNotFoundException.class"); testMap.put("cla...
public MemoryLRUCacheBytesIterator range(final String namespace, final Bytes from, final Bytes to) { return range(namespace, from, to, true); }
@Test public void shouldThrowIfNoPeekNextKeyRange() { final ThreadCache cache = setupThreadCache(0, 0, 10000L, false); shouldThrowIfNoPeekNextKey(() -> cache.range(namespace, Bytes.wrap(new byte[]{0}), Bytes.wrap(new byte[]{1}))); }
@Override public void deleteNotice(Long id) { // 校验是否存在 validateNoticeExists(id); // 删除通知公告 noticeMapper.deleteById(id); }
@Test public void testDeleteNotice_success() { // 插入前置数据 NoticeDO dbNotice = randomPojo(NoticeDO.class); noticeMapper.insert(dbNotice); // 删除 noticeService.deleteNotice(dbNotice.getId()); // 检查是否删除成功 assertNull(noticeMapper.selectById(dbNotice.getId())); ...
public Set<Analysis.AliasedDataSource> extractDataSources(final AstNode node) { new Visitor().process(node, null); return getAllSources(); }
@Test public void shouldHandleAliasedDataSources() { // Given: final AstNode stmt = givenQuery("SELECT * FROM TEST1 t;"); // When: extractor.extractDataSources(stmt); // Then: assertContainsAlias(SourceName.of("T")); }
@Override public void streamRequest(StreamRequest request, Callback<StreamResponse> callback) { streamRequest(request, new RequestContext(), callback); }
@Test(retryAnalyzer = ThreeRetries.class) // Known to be flaky in CI public void testIgnoreStreamRetry() throws Exception { SimpleLoadBalancer balancer = prepareLoadBalancer(Arrays.asList("http://test.linkedin.com/retry1", "http://test.linkedin.com/good"), HttpClientFactory.UNLIMITED_CLIENT_REQUEST_RETR...
public EclipseProfile getPublicProfile(String personId) { checkApiUrl(); var urlTemplate = eclipseApiUrl + "account/profile/{personId}"; var uriVariables = Map.of("personId", personId); var headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));...
@Test public void testGetPublicProfile() throws Exception { var urlTemplate = "https://test.openvsx.eclipse.org/account/profile/{personId}"; Mockito.when(restTemplate.exchange(eq(urlTemplate), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class), eq(Map.of("personId", "test")))) ...
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception { return fromXmlPartial(toInputStream(partial, UTF_8), o); }
@Test void shouldLoadIgnoresFromP4Partial() throws Exception { String gitPartial = """ <p4 port="localhost:8080"> <filter> <ignore pattern="x"/> </filter> ...
public static String getSnapshotPath(String snapshottableDir, String snapshotRelativePath) { final StringBuilder b = new StringBuilder(snapshottableDir); if (b.charAt(b.length() - 1) != Path.SEPARATOR_CHAR) { b.append(Path.SEPARATOR); } return b.append(HdfsConstants.DOT_SNAPSHOT_DIR) ...
@Test (timeout=60000) public void testUpdateDirectory() throws Exception { Path dir = new Path("/dir"); Path sub = new Path(dir, "sub"); Path subFile = new Path(sub, "file"); DFSTestUtil.createFile(hdfs, subFile, BLOCKSIZE, REPLICATION, seed); FileStatus oldStatus = hdfs.getFileStatus(sub); ...
public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; }
@Test void testIsEmpty() { assertTrue(StringUtils.isEmpty(null)); assertTrue(StringUtils.isEmpty("")); assertFalse(StringUtils.isEmpty(" ")); assertFalse(StringUtils.isEmpty("bob")); assertFalse(StringUtils.isEmpty(" bob ")); }
public static boolean matchDomain(String name, String pattern) { final int index = pattern.indexOf('*'); if (index == -1) { return name.equals(pattern); } else { String[] names = name.split("\\."); String[] patterns = pattern.split("\\."); if (patt...
@Test public void testMatchDomain() { assertTrue(AddressUtil.matchDomain("hazelcast.com", "hazelcast.com")); assertTrue(AddressUtil.matchDomain("hazelcast.com", "*.com")); assertTrue(AddressUtil.matchDomain("jobs.hazelcast.com", "*.hazelcast.com")); assertTrue(AddressUtil.matchDomain...
@CanIgnoreReturnValue @Override public JsonWriter value(String value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; }
@Test public void testBoolMaisValue() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); Boolean bool = true; assertThat(writer.value(bool)).isEqualTo(writer); }
@Override public String getValueFromText(String text) { return text; }
@Test public void getValueFromText() { for (String text : Arrays.asList("a", null, "b", "")) { assertSame(text, render.getValueFromText(text)); } }
protected void hideModel(EpoxyModel<?> model) { showModel(model, false); }
@Test public void testHideModel() { TestModel testModel = new TestModel(); testAdapter.addModels(testModel); testAdapter.hideModel(testModel); verify(observer).onItemRangeChanged(0, 1, null); assertFalse(testModel.isShown()); checkDifferState(); }
@Override public Response postDelegationToken(DelegationToken tokenData, HttpServletRequest hsr) throws AuthorizationException, IOException, InterruptedException, Exception { if (tokenData == null || hsr == null) { RouterAuditLogger.logFailure(getUser().getShortUserName(), POST_DELEGATION_TOKEN, ...
@Test public void testPostDelegationToken() throws Exception { Long now = Time.now(); DelegationToken token = new DelegationToken(); token.setRenewer(TEST_RENEWER); Principal principal = mock(Principal.class); when(principal.getName()).thenReturn(TEST_RENEWER); HttpServletRequest request = ...
public static List<Tab> getTabsFromJson(@Nullable final String tabsJson) throws InvalidJsonException { if (tabsJson == null || tabsJson.isEmpty()) { return getDefaultTabs(); } final List<Tab> returnTabs = new ArrayList<>(); final JsonObject outerJsonObject; ...
@Test public void testInvalidRead() { final List<String> invalidList = Arrays.asList( "{\"notTabsArray\":[]}", "{invalidJSON]}", "{}" ); for (final String invalidContent : invalidList) { try { TabsJsonHelper.getTabs...
@Override public TableStatistics getTableStatistics( ConnectorSession session, SchemaTableName table, Map<String, ColumnHandle> columns, Map<String, Type> columnTypes, List<HivePartition> partitions) { if (!isStatisticsEnabled(session)) { ...
@Test public void testGetTableStatistics() { String partitionName = "p1=string1/p2=1234"; PartitionStatistics statistics = PartitionStatistics.builder() .setBasicStatistics(new HiveBasicStatistics(OptionalLong.empty(), OptionalLong.of(1000), OptionalLong.of(5000), OptionalLong.em...
@Override public void init(SubsetConfiguration metrics2Properties) { properties = metrics2Properties; basePath = new Path(properties.getString(BASEPATH_KEY, BASEPATH_DEFAULT)); source = properties.getString(SOURCE_KEY, SOURCE_DEFAULT); ignoreError = properties.getBoolean(IGNORE_ERROR_KEY, DEFAULT_IGNO...
@Test public void testInit() { ConfigBuilder builder = new ConfigBuilder(); SubsetConfiguration conf = builder.add("sink.roll-interval", "10m") .add("sink.roll-offset-interval-millis", "1") .add("sink.basepath", "path") .add("sink.ignore-error", "true") ...
public void validate() throws TelegramApiException { if (useHttps) { File file = new File(keyStorePath); if (!file.exists() || !file.canRead()) { throw new TelegramApiException("Can't find or access server keystore file."); } } }
@Test public void testWhenHttpsEnabledAndKeyStoreFileNotPresentExceptionIsRaised() { WebhookOptions webhookOptions = new WebhookOptions(); webhookOptions.setUseHttps(true); webhookOptions.setKeyStorePath("/Random/path"); try { webhookOptions.validate(); fail("...
@Override public List<?> deserialize(final String topic, final byte[] bytes) { if (bytes == null) { return null; } try { final String recordCsvString = new String(bytes, StandardCharsets.UTF_8); final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat) .ge...
@Test public void shouldDeserializeNegativeDecimalSerializedAsNumber() { // Given: final PersistenceSchema schema = persistenceSchema( column("cost", SqlTypes.decimal(4, 2)) ); final KsqlDelimitedDeserializer deserializer = createDeserializer(schema); final byte[] bytes = "-1.12"...
@Override public int read(long position, byte[] buffer, int offset, int length) throws IOException { // When bufferedPreadDisabled = true, this API does not use any shared buffer, // cursor position etc. So this is implemented as NOT synchronized. HBase // kind of random reads on a shared file input...
@Test public void testReadAheadManagerForFailedReadAhead() throws Exception { AbfsClient client = getMockAbfsClient(); AbfsRestOperation successOp = getMockRestOp(); // Stub : // Read request leads to 3 readahead calls: Fail all 3 readahead-client.read() // Actual read request fails with the fail...
public ZFrame duplicate() { return new ZFrame(this.data); }
@Test public void testZFrameEquals() { ZFrame f = new ZFrame("Hello".getBytes()); ZFrame clone = f.duplicate(); assertThat(clone, is(f)); }
public static int getProcessorsCount() { int processorsCount = 0; String processorsCountPreSet = getProperty(PROCESSORS_PROP_NAME, PROCESSORS_ENV_NAME); if (processorsCountPreSet != null) { try { processorsCount = Integer.parseInt(processorsCountPreSet); }...
@Test void getProcessorsCount() { int processorsCount = PropertyUtils.getProcessorsCount(); assertNotNull(processorsCount); }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (bizConfig.isAdminServiceAccessControlEnabled()) { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res...
@Test public void testWithAccessControlDisabled() throws Exception { when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(false); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(filterCha...
@RequestMapping("/server") public ResponseEntity server() { ObjectNode result = JacksonUtils.createEmptyJsonNode(); result.put("msg", "Hello! I am Nacos-Naming and healthy! total services: " + MetricsMonitor.getDomCountMonitor() + ", local port:" + EnvUtil.getPort()); return ...
@Test void testServer() { ResponseEntity responseEntity = healthController.server(); assertEquals(200, responseEntity.getStatusCodeValue()); }
public static boolean exceedsPersistentQueryCapacity( final KsqlExecutionContext executionContext, final KsqlConfig ksqlConfig ) { return executionContext.getPersistentQueries().size() > getQueryLimit(ksqlConfig); }
@Test public void shouldNotReportCapacityExceededIfReached() { // Given: givenActivePersistentQueries(2); givenQueryLimit(2); // Then: assertThat(QueryCapacityUtil.exceedsPersistentQueryCapacity(ksqlEngine, ksqlConfig), equalTo(false)); }
public StepBreakpoint addStepBreakpoint( String workflowId, long version, long instanceId, long runId, String stepId, long stepAttemptId, User user) { final String revisedWorkflowId = getRevisedWorkflowId(workflowId, stepId, true); return withMetricLogError( () ...
@Test public void testAddBreakpoint() { when(workflowDao.getWorkflowDefinition(anyString(), anyString())).thenReturn(wfd); StepBreakpoint bp = maestroStepBreakpointDao.addStepBreakpoint( TEST_WORKFLOW_ID2, TEST_WORKFLOW_VERSION1, TEST_WORKFLOW_INSTANCE1, ...
public void validate(OptionRule rule) { List<RequiredOption> requiredOptions = rule.getRequiredOptions(); for (RequiredOption requiredOption : requiredOptions) { validate(requiredOption); for (Option<?> option : requiredOption.getOptions()) { if (SingleChoiceOpti...
@Test public void testAbsolutelyRequiredOption() { OptionRule rule = OptionRule.builder().required(TEST_PORTS, KEY_USERNAME, KEY_PASSWORD).build(); Map<String, Object> config = new HashMap<>(); Executable executable = () -> validate(config, rule); // absent c...
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) { return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName); }
@Test public void of_equalityNull() { String urnA = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208-1SchedulerTask"; assertNotNull(ScheduledTaskHandler.of(urnA)); }
public static ConfigRemoveResponse buildFailResponse(String errorMsg) { ConfigRemoveResponse removeResponse = new ConfigRemoveResponse(); removeResponse.setResultCode(ResponseCode.FAIL.getCode()); removeResponse.setMessage(errorMsg); return removeResponse; }
@Override @Test public void testSerializeFailResponse() throws JsonProcessingException { ConfigRemoveResponse configRemoveResponse = ConfigRemoveResponse.buildFailResponse("Fail"); String json = mapper.writeValueAsString(configRemoveResponse); assertTrue(json.contains("\"resultCode\":" +...
public void registerCredentialListener(CredentialListener listener) { this.listener = listener; }
@Test void testRegisterCredentialListener() { CredentialListener expect = mock(CredentialListener.class); CredentialService credentialService1 = CredentialService.getInstance(); credentialService1.registerCredentialListener(expect); Credentials newCredentials = new Credentials(); ...
public void createFolder() throws Exception { try { Collection<UIRepositoryDirectory> directories = folderTree.getSelectedItems(); if ( directories == null || directories.size() == 0 ) { return; } UIRepositoryDirectory selectedFolder = directories.iterator().next(); // First...
@Test public void shouldNotCreateFolderOnCloseCreationDialog() throws Exception { XulPromptBox prompt = new XulPromptBoxMock( XulDialogCallback.Status.CANCEL ); when( document.createElement( PROMPTBOX ) ).thenReturn( prompt ); controller.createFolder(); assertTrue( directoryMap.isEmpty() ); veri...
public static Write write() { return new AutoValue_RabbitMqIO_Write.Builder() .setExchangeDeclare(false) .setQueueDeclare(false) .build(); }
@Test public void testWriteQueue() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = RabbitMqTestUtils.generateRecords(maxNumRecords).stream() .map(RabbitMqMessage::new) .collect(Collectors.toList()); p.apply(Create.of(data)) .apply( ...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String fqn = reader.readLine(); List<Object> arguments = getArguments(reader); ReturnObject returnObject = invokeConstructor(fqn, arguments); String returnCommand = Protocol....
@Test public void testWrongConstructor() { String inputCommand = "py4j.examples.Stack\ni5\ne\n"; try { command.execute("i", new BufferedReader(new StringReader(inputCommand)), writer); assertTrue(sWriter.toString().startsWith("!x")); } catch (Exception e) { e.printStackTrace(); fail(); } }
@Override public void handle(TaskEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing " + event.getTaskID() + " of type " + event.getType()); } try { writeLock.lock(); TaskStateInternal oldState = getInternalState(); try { stateMachine.doTransition(eve...
@Test public void testKillSuccessfulTask() { LOG.info("--- START: testKillSuccesfulTask ---"); mockTask = createMockTask(TaskType.MAP); TaskId taskId = getNewTaskID(); scheduleTaskAttempt(taskId); launchTaskAttempt(getLastAttempt().getAttemptId()); commitTaskAttempt(getLastAttempt().getAttempt...
public Object resolve(final Expression expression) { return new Visitor().process(expression, null); }
@Test public void shouldThrowIfCannotParseDate() { // Given: final SqlType type = SqlTypes.DATE; final Expression exp = new StringLiteral("abc"); // When: final KsqlException e = assertThrows( KsqlException.class, () -> new GenericExpressionResolver(type, FIELD_NAME, registry, con...
public byte[] getBytes() { return bytes; }
@Test public void testGetBytes() throws Exception { for (int i = 0; i < 10000; i++) { // generate a random string String before = getTestString(); // Check that the bytes are stored correctly in Modified-UTF8 format. // Note that the DataInput and DataOutput interfaces convert between ...
public static Date parseTM(TimeZone tz, String s, DatePrecision precision) { return parseTM(tz, s, false, precision); }
@Test public void testParseTMacrnema() { DatePrecision precision = new DatePrecision(); assertEquals(0, DateUtils.parseTM(tz, "02:00:00", precision).getTime()); assertEquals(Calendar.SECOND, precision.lastField); }
public Optional<String> evaluate(Number toEvaluate) { return interval.isIn(toEvaluate) ? Optional.of(binValue) : Optional.empty(); }
@Test void evaluateOpenClosed() { KiePMMLDiscretizeBin kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(null, 20, CLOSURE.OPEN_CLOSED)); Optional<String> retrieved = kiePMMLDiscretizeBin...
public URI baseUri() { return server.configuration().baseUri(); }
@Test void run_selectIdp() { var baseUri = application.baseUri(); var sessionID = UUID.randomUUID().toString(); var response = given() .log() .all() .cookie("session_id", sessionID) .formParam("identityProvider", "") .when() ...
public File getLogDirectory() { return logDirectory; }
@Test public void getLogDirectory_is_configured_with_non_nullable_PATH_LOG_variable() throws IOException { File sqHomeDir = temp.newFolder(); File logDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH...
@Override public BackgroundException map(final SardineException failure) { final StringBuilder buffer = new StringBuilder(); switch(failure.getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_MULTI_STATUS: // HTTP method status this.ap...
@Test public void testMap() { Assert.assertEquals(LoginFailureException.class, new DAVExceptionMappingService().map(new SardineException("m", 401, "r")).getClass()); assertEquals(AccessDeniedException.class, new DAVExceptionMappingService().map(new SardineException("m", 403, ...
public LeaderInformation forComponentIdOrEmpty(String componentId) { return forComponentId(componentId).orElse(LeaderInformation.empty()); }
@Test void testForComponentIdOrEmpty() { final String componentId = "component-id"; final LeaderInformation leaderInformation = LeaderInformation.known(UUID.randomUUID(), "address"); assertThat( LeaderInformationRegister.of(componentId, leaderInformati...