focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public int launch(AgentLaunchDescriptor descriptor) { LogConfigurator logConfigurator = new LogConfigurator("agent-launcher-logback.xml"); return logConfigurator.runWithLogger(() -> doLaunch(descriptor)); }
@Test @DisabledOnOs(OS.WINDOWS) public void should_NOT_Download_TfsImplJar_IfTheCurrentJarIsUpToDate() throws Exception { TEST_AGENT_LAUNCHER.copyTo(AGENT_LAUNCHER_JAR); TEST_AGENT.copyTo(AGENT_BINARY_JAR); TEST_TFS_IMPL.copyTo(TFS_IMPL_JAR); assertTrue(TFS_IMPL_JAR.setLastModif...
@Override public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) { final ModelId modelId = entityDescriptor.id(); final Optional<NotificationDto> notificationDto = notificationService.get(modelId.id()); if (!notificationDto.isPresent(...
@Test @MongoDBFixtures("NotificationFacadeTest.json") public void exportEntity() { final ModelId id = ModelId.of("5d4d33753d27460ad18e0c4d"); final EntityDescriptor descriptor = EntityDescriptor.create(id, ModelTypes.NOTIFICATION_V1); final EntityDescriptorIds entityDescriptorIds = Entit...
@Override public Mono<Long> delete(final long id) { return Mono.zip( dataSourceRepository.existsByNamespace(id), collectorRepository.existsByNamespace(id), termRepository.existsByNamespace(id), dataEntityRepository.existsNonDeletedByNamespaceId...
@Test @DisplayName("Tries to delete a namespace which is tied with existing data entity and fails with an error") public void testDeleteTiedNamespaceWithDataEntity() { final long namespaceId = 1L; when(collectorRepository.existsByNamespace(eq(namespaceId))).thenReturn(Mono.just(false)); ...
public static Object construct(String className) throws JMeterException { Object instance = null; try { instance = ClassUtils.getClass(className).getDeclaredConstructor().newInstance(); } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) { ...
@Test public void testConstructStringString() throws JMeterException { String dummy = (String) ClassTools.construct("java.lang.String", "hello"); assertNotNull(dummy); assertEquals("hello", dummy); }
@Override public Boolean mSet(Map<byte[], byte[]> tuple) { if (isQueueing() || isPipelined()) { for (Entry<byte[], byte[]> entry: tuple.entrySet()) { write(entry.getKey(), StringCodec.INSTANCE, RedisCommands.SET, entry.getKey(), entry.getValue()); } return...
@Test public void testMSet() { testInCluster(connection -> { Map<byte[], byte[]> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(("test" + i).getBytes(), ("test" + i*100).getBytes()); } connection.mSet(map); for (Map.E...
public static Version loadApiVersion(System2 system) { return getVersion(system, SONAR_API_VERSION_FILE_PATH); }
@Test void throw_ISE_if_fail_to_load_version() throws Exception { when(system.getResource(anyString())).thenReturn(new File("target/unknown").toURI().toURL()); assertThatThrownBy(() -> MetadataLoader.loadApiVersion(system)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Can not...
public void readErrorOf(InputStream in) { context.console().readErrorOf(in); }
@Test public void shouldDelegateReadErrorOfToConsole() { InputStream inputStream = mock(InputStream.class); consoleLogger.readErrorOf(inputStream); verify(mockedConsole).readErrorOf(inputStream); }
private boolean checkForError(Message message, Response<?> response) { if (response.hasError()) { int code = response.getError().getCode(); String data = response.getError().getData(); String messages = response.getError().getMessage(); message.setHeader(Web3jCons...
@Test public void checkForErrorTest() throws Exception { Web3ClientVersion response = Mockito.mock(Web3ClientVersion.class); Mockito.when(mockWeb3j.web3ClientVersion()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.hasError()).thenRetur...
@Override public void handle(ContainerLauncherEvent event) { try { eventQueue.put(event); } catch (InterruptedException e) { throw new YarnRuntimeException(e); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test(timeout = 5000) public void testContainerCleaned() throws Exception { LOG.info("STARTING testContainerCleaned"); CyclicBarrier startLaunchBarrier = new CyclicBarrier(2); CyclicBarrier completeLaunchBarrier = new CyclicBarrier(2); AppContext ...
@Override public Expression getExpression(String tableName, Alias tableAlias) { // 只有有登陆用户的情况下,才进行数据权限的处理 LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser == null) { return null; } // 只有管理员类型的用户,才进行数据权限的处理 if (ObjectUtil.notEqual(...
@Test // 拼接 Dept 和 User 的条件(字段都不符合) public void testGetExpression_noDeptColumn_noSelfColumn() { try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock = mockStatic(SecurityFrameworkUtils.class)) { // 准备参数 String tableName = "t_user"; Ali...
public static List<File> loopFiles(String path, FileFilter fileFilter) { return loopFiles(file(path), fileFilter); }
@Test @Disabled public void loopFilesTest() { final List<File> files = FileUtil.loopFiles("d:/"); for (final File file : files) { Console.log(file.getPath()); } }
public EtcdClient(final String url, final long ttl, final long timeout) { this.client = Client.builder().endpoints(url.split(",")).build(); this.ttl = ttl; this.timeout = timeout; initLease(); }
@Test public void etcdClientTest() { try (MockedStatic<Client> clientMockedStatic = mockStatic(Client.class)) { final ClientBuilder clientBuilder = mock(ClientBuilder.class); clientMockedStatic.when(Client::builder).thenReturn(clientBuilder); when(clientBuilder.endpoints(...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { final EueApiClient client = new EueApiClient(session); final UiFsModel response; final String resourceId = fileid.getFileId(file); swi...
@Test public void testRoot() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final PathAttributes attr = new EueAttributesFinderFeature(session, fileid).find(new Path("/", EnumSet.of(Path.Type.directory))); assertNotEquals(PathAttributes.EMPTY, att...
public static List<String> computeLangFromLocale(Locale locale) { final List<String> resourceNames = new ArrayList<>(5); if (StringUtils.isBlank(locale.getLanguage())) { throw new IllegalArgumentException( "Locale \"" + locale + "\" " + "cannot be used as...
@Test void computeLangFromLocaleWhenLanguageIsEmpty() { assertThatThrownBy(() -> { LanguageUtils.computeLangFromLocale(Locale.forLanguageTag("")); }).isInstanceOf(IllegalArgumentException.class) .hasMessage("Locale \"\" cannot be used as it does not specify a language."); ...
public Generics(Fury fury) { this.fury = fury; }
@Test public void testGenerics() throws NoSuchFieldException { Fury fury = Fury.builder().withLanguage(Language.JAVA).build(); Generics generics = new Generics(fury); { GenericType genericType = GenericType.build(Test4.class, Test2.class.getField("fromFieldNested").getGenericType()); ...
@Override public Map<String, StepTransition> translate(WorkflowInstance workflowInstance) { WorkflowInstance instance = objectMapper.convertValue(workflowInstance, WorkflowInstance.class); if (instance.getRunConfig() != null) { if (instance.getRunConfig().getPolicy() == RunPolicy.RESTART_FROM_INCOMPLET...
@Test public void testTranslateForRestartFromSpecificWithCompleteBranch() { instance.getRuntimeWorkflow().getSteps().get(2).getTransition().getSuccessors().remove("job.2"); instance .getAggregatedInfo() .getStepAggregatedViews() .put("job.2", StepAggregatedView.builder().status(StepIns...
public void setAttribute(final String key, Object value) { setAttributeObject(key, value); }
@Test(expected=AttributeAlreadySetException.class) public void cannotSetDifferentAttributeValue() { Entry entry = new Entry(); entry.setAttribute("key", "value"); entry.setAttribute("key", "value2"); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { return new DeepBoxesListService().list(directory, listener); } if(containerService.isDeepbox(directory)) { // in DeepBox ...
@Test public void testListInbox() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path queue = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Inbox", EnumSet.of(Path.Type.directory)); final AttributedList<Path> list = new DeepboxListService(session...
static <T extends Type> String buildMethodSignature( String methodName, List<TypeReference<T>> parameters) { StringBuilder result = new StringBuilder(); result.append(methodName); result.append("("); String params = parameters.stream().map(Utils::getTypeName)...
@Test void testBuildMethodSignatureWithDynamicStructs() { assertEquals( "nazzEvent((((string,string)[])[],uint256),(string,string))", EventEncoder.buildMethodSignature( AbiV2TestFixture.nazzEvent.getName(), AbiV2TestFixture.nazz...
public AccessPrivilege getAccessPrivilege(InetAddress addr) { return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName()); }
@Test public void testCidrLongRO() { NfsExports matcher = new NfsExports(CacheSize, ExpirationPeriod, "192.168.0.0/255.255.252.0"); Assert.assertEquals(AccessPrivilege.READ_ONLY, matcher.getAccessPrivilege(address1, hostname1)); Assert.assertEquals(AccessPrivilege.NONE, matcher.ge...
@Override public LookupResult<BrokerKey> handleResponse(Set<BrokerKey> keys, AbstractResponse abstractResponse) { validateLookupKeys(keys); MetadataResponse response = (MetadataResponse) abstractResponse; MetadataResponseData.MetadataResponseBrokerCollection brokers = response.data().broker...
@Test public void testHandleResponseWithInvalidLookupKeys() { AllBrokersStrategy strategy = new AllBrokersStrategy(logContext); AllBrokersStrategy.BrokerKey key1 = new AllBrokersStrategy.BrokerKey(OptionalInt.empty()); AllBrokersStrategy.BrokerKey key2 = new AllBrokersStrategy.BrokerKey(Opti...
@Override public void start() { builtInQProfileRepository.initialize(); }
@Test void start_initializes_DefinedQProfileRepository() { underTest.start(); assertThat(builtInQProfileRepositoryRule.isInitialized()).isTrue(); }
public void runMigrations() { List<SqlMigration> migrationsToRun = getMigrations() .filter(migration -> migration.getFileName().endsWith(".sql")) .sorted(comparing(SqlMigration::getFileName)) .filter(this::isNewMigration) .collect(toList()); ...
@Test void testH2ValidateWithTablesInWrongSchema() { final JdbcDataSource dataSource = createH2DataSource("jdbc:h2:/tmp/test;INIT=CREATE SCHEMA IF NOT EXISTS schema1\\;CREATE SCHEMA IF NOT EXISTS schema2"); final DatabaseCreator databaseCreatorForSchema1 = new DatabaseCreator(dataSource, "schema1.pr...
@Override public void check(final EncryptRule encryptRule, final ShardingSphereSchema schema, final SQLStatementContext sqlStatementContext) { ShardingSpherePreconditions.checkState(JoinConditionsEncryptorComparator.isSame(((WhereAvailable) sqlStatementContext).getJoinConditions(), encryptRule), ...
@Test void assertGenerateSQLTokensWhenJoinConditionUseDifferentEncryptor() { assertThrows(UnsupportedSQLOperationException.class, () -> new EncryptPredicateColumnSupportedChecker().check(EncryptGeneratorFixtureBuilder.createEncryptRule(), null, EncryptGeneratorFixtureBuilder.createSelectStat...
@Override public Set<EntityExcerpt> listEntityExcerpts() { return lookupTableService.findAll().stream() .map(this::createExcerpt) .collect(Collectors.toSet()); }
@Test @MongoDBFixtures("LookupTableFacadeTest.json") public void listEntityExcerpts() { final EntityExcerpt expectedEntityExcerpt = EntityExcerpt.builder() .id(ModelId.of("5adf24dd4b900a0fdb4e530d")) .type(ModelTypes.LOOKUP_TABLE_V1) .title("HTTP DSV witho...
public static byte[] toArray(ByteBuffer buffer) { return toArray(buffer, 0, buffer.remaining()); }
@Test public void toArrayDirectByteBuffer() { byte[] input = {0, 1, 2, 3, 4}; ByteBuffer buffer = ByteBuffer.allocateDirect(5); buffer.put(input); buffer.rewind(); assertArrayEquals(input, Utils.toArray(buffer)); assertEquals(0, buffer.position()); assertArr...
public static HttpRequest newJDiscRequest(CurrentContainer container, HttpServletRequest servletRequest) { try { var jettyRequest = (Request) servletRequest; var jdiscHttpReq = HttpRequest.newServerRequest( container, getUri(servletRequest), ...
@Test final void illegal_host_throws_requestexception3() { try { HttpRequestFactory.newJDiscRequest( new MockContainer(), createMockRequest("http", "*", "/foo", "")); fail("Above statement should throw"); } catch (RequestException e) { ...
@Override public V load(K key) { awaitSuccessfulInit(); try (SqlResult queryResult = sqlService.execute(queries.load(), key)) { Iterator<SqlRow> it = queryResult.iterator(); V value = null; if (it.hasNext()) { SqlRow sqlRow = it.next(); ...
@Test public void whenMapLoaderInitCalledOnNonMaster_thenInitAndLoadValue() { ObjectSpec spec = objectProvider.createObject(mapName, false); objectProvider.insertItems(spec, 1); mapLoader = createMapLoader(instances()[1]); GenericRecord genericRecord = mapLoader.load(0); ass...
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback); return bean; }
@Test void beansWithoutMethodsAnnotatedWithRecurringAnnotationWillNotBeHandled() { // GIVEN final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor(); // WHEN recurringJobPostProcessor.postProcessAfterInitialization(new MyServiceWithoutRecurringAnnot...
public static long quorumPosition(final ClusterMember[] members, final long[] rankedPositions) { final int length = rankedPositions.length; for (int i = 0; i < length; i++) { rankedPositions[i] = 0; } for (final ClusterMember member : members) { ...
@Test void shouldRankClusterStart() { assertThat(quorumPosition(members, rankedPositions), is(0L)); }
@Override public V load(K k) throws CacheLoaderException { long startNanos = Timer.nanos(); try { return delegate.get().load(k); } finally { loadProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void load() { String key = "key"; String value = "value"; when(delegate.load(key)).thenReturn(value); String result = cacheLoader.load(key); assertSame(value, result); assertProbeCalledOnce("load"); }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServ...
@Test void testTpsCheckException() throws Exception { HttpTpsCheckRequestParserRegistry.register(new HttpTpsCheckRequestParser() { @Override public TpsCheckRequest parse(HttpServletRequest httpServletRequest) { return new TpsCheckRequest(); } ...
public Optional<Example<T>> generateExample(ColumnarIterator.Row row, boolean outputRequired) { List<String> responseValues = responseProcessor.getFieldNames().stream() .map(f -> row.getRowData().getOrDefault(f, "")) .collect(Collectors.toList()); Optional<T> labelOpt = ...
@Test public void replaceNewlinesWithSpacesTest() { final Pattern BLANK_LINES = Pattern.compile("(\n[\\s-]*\n)+"); final Function<CharSequence, CharSequence> newLiner = (CharSequence charSequence) -> { if (charSequence == null || charSequence.length() == 0) { return char...
@Override public void close() throws IOException { if (closed) { return; } super.close(); closeStream(); closed = true; }
@Test public void testClose() throws Exception { OSSURI uri = new OSSURI(location("closed.dat")); SeekableInputStream closed = new OSSInputStream(ossClient().get(), uri); closed.close(); assertThatThrownBy(() -> closed.seek(0)) .isInstanceOf(IllegalStateException.class) .hasMessageCont...
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testUpdateFetchPositionResetToDefaultOffset() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0); client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.EARLIEST_TIMESTAMP, validLeaderEpoch), listOffsetRe...
@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the re...
@Test public void testPostNewDeploymentBarFile() throws Exception { try { // Create zip with bpmn-file and resource ByteArrayOutputStream zipOutput = new ByteArrayOutputStream(); ZipOutputStream zipStream = new ZipOutputStream(zipOutput); // Add bpmn-xml ...
DateRange getRange(String dateRangeString) throws ParseException { if (dateRangeString == null || dateRangeString.isEmpty()) return null; String[] dateArr = dateRangeString.split("-"); if (dateArr.length > 2 || dateArr.length < 1) return null; // throw new Illega...
@Test public void testParseReverseDateRangeWithoutYearAndDay() throws ParseException { DateRange dateRange = dateRangeParser.getRange("Sep-Mar"); assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 31))); assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.SEPTEMBER, 1))...
@VisibleForTesting protected static CacheQuota generateCacheQuota(HiveSplit hiveSplit) { Optional<DataSize> quota = hiveSplit.getCacheQuotaRequirement().getQuota(); switch (hiveSplit.getCacheQuotaRequirement().getCacheQuotaScope()) { case GLOBAL: return new CacheQuota...
@Test public void testGenerateCacheQuota() { HiveClientConfig config = new HiveClientConfig(); HiveFileSplit fileSplit = new HiveFileSplit("file://test", 0, 10, 10, Instant.now().toEpochMilli(), Optional.empty(), ...
public void publishRestartEvents(Pod pod, RestartReasons reasons) { MicroTime k8sEventTime = new MicroTime(K8S_MICROTIME.format(ZonedDateTime.now(clock))); ObjectReference podReference = createPodReference(pod); try { for (RestartReason reason : reasons) { String not...
@Test void testOneEventPublishedPerReason() { Pod mockPod = Mockito.mock(Pod.class); ObjectMeta mockPodMeta = new ObjectMetaBuilder().withName("pod").withNamespace("ns").build(); when(mockPod.getMetadata()).thenReturn(mockPodMeta); KubernetesClient client = mock(KubernetesClient.cl...
public static PostgreSQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find PostgreSQL type '%s' in column type when process binary protocol value", binaryColumnType); return ...
@Test void assertGetDoubleBinaryProtocolValue() { PostgreSQLBinaryProtocolValue binaryProtocolValue = PostgreSQLBinaryProtocolValueFactory.getBinaryProtocolValue(PostgreSQLColumnType.FLOAT8); assertThat(binaryProtocolValue, instanceOf(PostgreSQLDoubleBinaryProtocolValue.class)); }
public CompletableFuture<Integer> read(ByteBuffer buf, long offset, long len, FileId fileId, String ufsPath, UfsReadOptions options) { Objects.requireNonNull(buf); if (offset < 0 || len < 0 || len > buf.remaining()) { throw new OutOfRangeRuntimeException(String.format( "offset is negative,...
@Test public void readPartialBlock() throws Exception { mUfsIOManager.read(TEST_BUF, 0, TEST_BLOCK_SIZE - 1, FIRST_BLOCK_ID, mTestFilePath, UfsReadOptions.getDefaultInstance()).get(); assertTrue(checkBuf(0, (int) TEST_BLOCK_SIZE - 1, TEST_BUF)); TEST_BUF.clear(); }
public final List<E> findAll(E key) { if (key == null || size() == 0) { return Collections.emptyList(); } ArrayList<E> results = new ArrayList<>(); int slot = slot(elements, key); for (int seen = 0; seen < elements.length; seen++) { Element element = eleme...
@Test public void testFindFindAllContainsRemoveOnEmptyCollection() { ImplicitLinkedHashMultiCollection<TestElement> coll = new ImplicitLinkedHashMultiCollection<>(); assertNull(coll.find(new TestElement(2))); assertFalse(coll.contains(new TestElement(2))); assertFalse(coll.remove(new...
@Bean public MetaDataHandler apacheDubboMetaDataHandler() { return new ApacheDubboMetaDataHandler(); }
@Test public void testApacheDubboMetaDataHandler() { applicationContextRunner.run(context -> { MetaDataHandler handler = context.getBean("apacheDubboMetaDataHandler", MetaDataHandler.class); assertNotNull(handler); } ); }
@Override public void collect(MetricsEmitter metricsEmitter) { for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) { MetricKey metricKey = entry.getKey(); KafkaMetric metric = entry.getValue(); try { collectMetric(metricsEmitter, metricKey...
@Test public void testMeasurableWithException() { metrics.addMetric(metricName, null, (config, now) -> { throw new RuntimeException(); }); collector.collect(testEmitter); List<SinglePointMetric> result = testEmitter.emittedMetrics(); //Verify only the global cou...
@Override public final int position() { return pos; }
@Test public void testPosition() { assertEquals(0, in.position()); }
@Override public String toString() { return String.format("%s,,", getType()); }
@Test void assertToString() { assertThat(new UnsupportedKeyIngestPosition().toString(), is("u,,")); }
@LiteralParameters("x") @ScalarOperator(EQUAL) @SqlType(StandardTypes.BOOLEAN) @SqlNullable public static Boolean equal(@SqlType("char(x)") Slice left, @SqlType("char(x)") Slice right) { return left.equals(right); }
@Test public void testEqual() { assertFunction("cast('foo' as char(3)) = cast('foo' as char(5))", BOOLEAN, true); assertFunction("cast('foo' as char(3)) = cast('foo' as char(3))", BOOLEAN, true); assertFunction("cast('foo' as char(3)) = cast('bar' as char(3))", BOOLEAN, false); a...
@Override public void open() throws Exception { mainInputActivityClock = new PausableRelativeClock(getProcessingTimeService().getClock()); TaskIOMetricGroup taskIOMetricGroup = getContainingTask().getEnvironment().getMetricGroup().getIOMetricGroup(); taskIOMetricGroup.registe...
@Test void testOpen() throws Exception { // Initialize the operator. operator.initializeState(context.createStateContext()); // Open the operator. operator.open(); // The source reader should have been assigned a split. assertThat(mockSourceReader.getAssignedSplits())...
public OpenConfigTransceiverHandler addConfig(OpenConfigConfigOfTransceiverHandler config) { modelObject.config(config.getModelObject()); return this; }
@Test public void testAddConfig() { // test Handler OpenConfigTransceiverHandler transceiver = new OpenConfigTransceiverHandler(parent); // call addConfig OpenConfigConfigOfTransceiverHandler config = new OpenConfigConfigOfTransceiverHandler(transceiver); // expected ModelO...
@Override public int getAttemptCount(int subtaskIndex) { Preconditions.checkArgument(subtaskIndex >= 0); if (subtaskIndex >= attemptCounts.size()) { return 0; } return attemptCounts.get(subtaskIndex); }
@Test void testGetAttemptCount() { final List<Integer> initialAttemptCounts = Arrays.asList(1, 2, 3); final DefaultSubtaskAttemptNumberStore subtaskAttemptNumberStore = new DefaultSubtaskAttemptNumberStore(initialAttemptCounts); assertThat(subtaskAttemptNumberStore.getAttemp...
@Override public CompletableFuture<Optional<BrokerLookupData>> assign(Optional<ServiceUnitId> topic, ServiceUnitId serviceUnit, LookupOptions options) { final String bundle = serv...
@Test public void testAssign() throws Exception { Pair<TopicName, NamespaceBundle> topicAndBundle = getBundleIsNotOwnByChangeEventTopic("test-assign"); TopicName topicName = topicAndBundle.getLeft(); NamespaceBundle bundle = topicAndBundle.getRight(); Optional<BrokerLookupData> broke...
@SuppressWarnings("unchecked") boolean contains(DiscreteResource resource) { return resource.valueAs(Object.class) .map(x -> codec.encode(x)) .map(rangeSet::contains) .orElse(false); }
@Test public void testContains() { DiscreteResource res1 = Resources.discrete(DID, PN, VID1).resource(); DiscreteResource res2 = Resources.discrete(DID, PN, VID2).resource(); DiscreteResource res3 = Resources.discrete(DID, PN, VID3).resource(); Set<DiscreteResource> resources = Immu...
@CanIgnoreReturnValue @Override public JsonWriter value(String value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; }
@Test public void testBoolValue() throws Exception { JsonTreeWriter writer = new JsonTreeWriter(); boolean bool = true; assertThat(writer.value(bool)).isEqualTo(writer); }
public static String getTagValue( Node n, KettleAttributeInterface code ) { return getTagValue( n, code.getXmlCode() ); }
@Test public void getTagValueWithNullNode() { assertNull( XMLHandler.getTagValue( null, "text" ) ); }
@Override public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { // ask for a mandatory type conversion to avoid a possible NPE beforehand as we do copy from the InputStream final InputStream is = exchange.getContext().getTypeConverter().mandat...
@Test public void testMarshalMandatoryConversionFailed() throws Exception { DataFormat dataFormat = new ZipDeflaterDataFormat(); try { dataFormat.marshal(new DefaultExchange(context), new Object(), new ByteArrayOutputStream()); fail("Should have thrown an exception"); ...
public final void setStrictness(Strictness strictness) { Objects.requireNonNull(strictness); this.strictness = strictness; }
@Test public void testCapitalizedNullFailWhenStrict() { JsonReader reader = new JsonReader(reader("NULL")); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextNull); assertThat(expected) .hasMessageThat() .startsWith( ...
@Override public boolean supportSchemaVersioning() { return true; }
@Test public void testSupportMultiVersioningSupportByDefault() { Assert.assertTrue(writerSchema.supportSchemaVersioning()); Assert.assertTrue(readerSchema.supportSchemaVersioning()); }
public PeriodStats plus(PeriodStats toAdd) { PeriodStats result = new PeriodStats(); result.messagesSent += this.messagesSent; result.messageSendErrors += this.messageSendErrors; result.bytesSent += this.bytesSent; result.messagesReceived += this.messagesReceived; result...
@Test void plus() { PeriodStats one = new PeriodStats(); one.messagesSent = 1; one.messageSendErrors = 2; one.bytesSent = 3; one.messagesReceived = 4; one.bytesReceived = 5; one.totalMessagesSent = 6; one.totalMessageSendErrors = 7; one.totalMe...
public synchronized Topology build() { return build(null); }
@Test public void shouldNotThrowNullPointerIfOptimizationsNotSpecified() { final Properties properties = new Properties(); final StreamsBuilder builder = new StreamsBuilder(); builder.build(properties); }
public void isNotIn(@Nullable Iterable<?> iterable) { checkNotNull(iterable); if (Iterables.contains(iterable, actual)) { failWithActual("expected not to be any of", iterable); } }
@Test public void isNotInFailure() { expectFailure.whenTesting().that("b").isNotIn(oneShotIterable("a", "b", "c")); assertFailureKeys("expected not to be any of", "but was"); assertFailureValue("expected not to be any of", "[a, b, c]"); }
public static HCatSchema getHCatSchemaFromTypeString(String typeString) throws HCatException { return getHCatSchema(TypeInfoUtils.getTypeInfoFromTypeString(typeString)); }
@Test public void testSimpleOperation() throws Exception { String typeString = "struct<name:string,studentid:int," + "contact:struct<phNo:string,email:string>," + "currently_registered_courses:array<string>," + "current_grades:map<string,string>," + "phNos:array<struct<phNo:string,...
@Override public AppToken createAppToken(long appId, String privateKey) { Algorithm algorithm = readApplicationPrivateKey(appId, privateKey); LocalDateTime now = LocalDateTime.now(clock); // Expiration period is configurable and could be greater if needed. // See https://developer.github.com/apps/buil...
@Test public void createAppToken_fails_with_IAE_if_privateKey_PKCS8_content_is_corrupted() { String corruptedPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEowIBAAKCAQEA6C29ZdvrwHOu7Eewv+xvUd4inCnACTzAHukHKTSY4R16+lRI\n" + "YC5qZ8Xo304J7lLhN4/d4Xnof3lDXZOHthVbJKik4fOuEGbTXTIcuFs3hdJtrJsb\n" + ...
public MailConfiguration getConfiguration() { if (configuration == null) { configuration = new MailConfiguration(getCamelContext()); } return configuration; }
@Test public void testMailEndpointsAreConfiguredProperlyWhenUsingPop() { MailEndpoint endpoint = checkEndpoint("pop3://james@myhost:110/subject"); MailConfiguration config = endpoint.getConfiguration(); assertEquals("pop3", config.getProtocol(), "getProtocol()"); assertEquals("myhost...
@Override public void saveProperty(DbSession session, PropertyDto property, @Nullable String userLogin, @Nullable String projectKey, @Nullable String projectName, @Nullable String qualifier) { // do nothing }
@Test public void insertProperty() { underTest.saveProperty(dbSession, propertyDto, null, null, null, null); assertNoInteraction(); }
public Resource getQueueResource(String queueName, Set<String> queueLabels, Resource clusterResource) { readLock.lock(); try { if (queueLabels.contains(ANY)) { return clusterResource; } Queue q = queueCollections.get(queueName); if (null == q) { return Resources.non...
@Test(timeout=5000) public void testGetQueueResource() throws Exception { Resource clusterResource = Resource.newInstance(9999, 1); /* * Node->Labels: * host1 : red * host2 : blue * host3 : yellow * host4 : */ mgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet...
public static String getMasterForEntry(JournalEntry entry) { if (entry.hasAddMountPoint() || entry.hasAsyncPersistRequest() || entry.hasAddSyncPoint() || entry.hasActiveSyncTxId() || entry.hasCompleteFile() || entry.hasDeleteFile() || entry.hasDeleteMountPoint() ...
@Test public void testUnknown() { mThrown.expect(IllegalStateException.class); JournalEntryAssociation.getMasterForEntry(JournalEntry.getDefaultInstance()); }
@Override public void consume(Update update) { super.consume(update); }
@Test void canProcessRepliesRegisteredInCollection() { Update firstUpdate = mock(Update.class); Message firstMessage = mock(Message.class); when(firstMessage.getText()).thenReturn(DefaultBot.FIRST_REPLY_KEY_MESSAGE); when(firstMessage.getChatId()).thenReturn(1L); Update secondUpdate = mock(Update...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetcherIgnoresControlRecords() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); // normal fetch assertEquals(1, sendFetches()); assertFalse(fetcher.hasCompletedFetches()); long producerId = 1; short...
@Override public void executeUpdate(final SetComputeNodeStateStatement sqlStatement, final ContextManager contextManager) { if ("DISABLE".equals(sqlStatement.getState())) { checkDisablingIsValid(contextManager, sqlStatement.getInstanceId()); } else { checkEnablingIsValid(cont...
@Test void assertExecuteUpdateWithCurrentUsingInstance() { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(contextManager.getComputeNodeInstanceContext().getInstance().getMetaData().getId()).thenReturn("instanceID"); assertThrows(UnsupportedSQLOperationEx...
@Override public boolean matchesJdbcUrl(String jdbcConnectionURL) { return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:postgresql:"); }
@Test void matchesJdbcURL() { assertThat(underTest.matchesJdbcUrl("jdbc:postgresql://localhost/sonar")).isTrue(); assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse(); }
int getCalculatedScale(String value) { int index = value.indexOf("."); return index == -1 ? 0 : value.length() - index - 1; }
@Test public void testGetCalculatedScale() { PinotResultSet pinotResultSet = new PinotResultSet(); int calculatedResult; calculatedResult = pinotResultSet.getCalculatedScale("1"); Assert.assertEquals(calculatedResult, 0); calculatedResult = pinotResultSet.getCalculatedScale("1.0"); Assert.as...
static void checkValidTableId(String idToCheck) { if (idToCheck.length() < MIN_TABLE_ID_LENGTH) { throw new IllegalArgumentException("Table ID cannot be empty. "); } if (idToCheck.length() > MAX_TABLE_ID_LENGTH) { throw new IllegalArgumentException( "Table ID " + idToChec...
@Test public void testCheckValidTableIdWhenIdIsTooLong() { char[] chars = new char[1025]; Arrays.fill(chars, 'a'); String s = new String(chars); assertThrows(IllegalArgumentException.class, () -> checkValidTableId(s)); }
@Override public List<PostDO> getPostList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } return postMapper.selectBatchIds(ids); }
@Test public void testGetPostList_idsAndStatus() { // mock 数据 PostDO postDO01 = randomPojo(PostDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); postMapper.insert(postDO01); // 测试 status 不匹配 PostDO postDO02 = randomPojo(PostDO.class, o -> o.setStatus(CommonSta...
public boolean overlaps(final BoundingBox pBoundingBox, double pZoom) { //FIXME this is a total hack but it works around a number of issues related to vertical map //replication and horiztonal replication that can cause polygons to completely disappear when //panning if (pZoom < 3) ...
@Test public void testDrawSetupLowZoom2() { BoundingBox view = new BoundingBox(83.17404, 142.74437, -18.14585, 7.73437); //in some tests, this was disappearing when panning left (westard) BoundingBox drawing = new BoundingBox(69.65708, 112.85162, 48.45835, 76.64063); Assert.assertTr...
@SuppressWarnings("checkstyle:npathcomplexity") public PartitionServiceState getPartitionServiceState() { PartitionServiceState state = getPartitionTableState(); if (state != SAFE) { return state; } if (!checkAndTriggerReplicaSync()) { return REPLICA_NOT_SYN...
@Test public void shouldNotBeSafe_whenMissingReplicasPresent() { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz = factory.newHazelcastInstance(); InternalPartitionServiceImpl partitionService = getNode(hz).partitionService; partitionServ...
Converter<E> compile() { head = tail = null; for (Node n = top; n != null; n = n.next) { switch (n.type) { case Node.LITERAL: addToList(new LiteralConverter<E>((String) n.getValue())); break; case Node.COMPOSITE_KEYWORD: ...
@Test public void testLiteral() throws Exception { Parser<Object> p = new Parser<Object>("hello"); Node t = p.parse(); Converter<Object> head = p.compile(t, converterMap); String result = write(head, new Object()); assertEquals("hello", result); }
@Override public Address getCaller() { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void testGetCaller() { dataEvent.getCaller(); }
public static boolean isSystemClass(String name, List<String> systemClasses) { boolean result = false; if (systemClasses != null) { String canonicalName = name.replace('/', '.'); while (canonicalName.startsWith(".")) { canonicalName=canonicalName.substring(1); } for (String c : s...
@Test public void testIsSystemClass() { testIsSystemClassInternal(""); }
static void unTarUsingJava(File inFile, File untarDir, boolean gzipped) throws IOException { InputStream inputStream = null; TarArchiveInputStream tis = null; try { if (gzipped) { inputStream = new GZIPInputStream(Files.newInputStream(inFile.toPath())); } else { ...
@Test(timeout = 30000) public void testUntarMissingFileThroughJava() throws Throwable { File dataDir = GenericTestUtils.getTestDir(); File tarFile = new File(dataDir, "missing; true"); File untarDir = new File(dataDir, "untarDir"); // java8 on unix throws java.nio.file.NoSuchFileException here; //...
@SuppressWarnings("unchecked") @Override public void configure(Map<String, ?> configs) throws KafkaException { if (sslEngineFactory != null) { throw new IllegalStateException("SslFactory was already configured."); } this.endpointIdentification = (String) configs.get(SslConfig...
@Test public void testUntrustedKeyStoreValidationFails() throws Exception { File trustStoreFile1 = TestUtils.tempFile("truststore1", ".jks"); File trustStoreFile2 = TestUtils.tempFile("truststore2", ".jks"); Map<String, Object> sslConfig1 = sslConfigsBuilder(ConnectionMode.SERVER) ...
@Override @SuppressWarnings("unchecked") public void onApplicationEvent(@NotNull final DataChangedEvent event) { for (DataChangedListener listener : listeners) { if ((!(listener instanceof AbstractDataChangedListener)) && clusterProperties.isEnabled() ...
@Test public void onApplicationEventWithAppAuthConfigGroupTest() { when(clusterProperties.isEnabled()).thenReturn(true); when(shenyuClusterSelectMasterService.isMaster()).thenReturn(true); ConfigGroupEnum configGroupEnum = ConfigGroupEnum.APP_AUTH; DataChangedEvent dataChangedEvent =...
public static boolean containsIgnoreCase(List<String> list, String str) { for (String i : list) { if (i.equalsIgnoreCase(str)) { return true; } } return false; }
@Test void testContainsIgnoreCase() { List<String> list = Arrays.asList("foo", "bar"); assertTrue(StringUtils.containsIgnoreCase(list, "foo")); assertTrue(StringUtils.containsIgnoreCase(list, "Foo")); assertFalse(StringUtils.containsIgnoreCase(list, "baz")); }
@Override public Host filter(final KsqlHostInfo host) { if (!heartbeatAgent.isPresent()) { return Host.include(host); } final Map<KsqlHostInfo, HostStatus> allHostsStatus = heartbeatAgent.get().getHostsStatus(); final HostStatus status = allHostsStatus.get(host); if (status == null) { ...
@Test public void shouldFilterStandbyAlive() { // Given: allHostsStatus = ImmutableMap.of( activeHost, HOST_DEAD, standByHost1, HOST_ALIVE, standByHost2, HOST_DEAD ); when(heartbeatAgent.getHostsStatus()).thenReturn(allHostsStatus); // When: final Host filterActive = l...
public static HealthConfig load(String configName) { return new HealthConfig(configName); }
@Test public void testLoad() { HealthConfig config = HealthConfig.load(); assert(config != null); }
public static String formatXml(String xml){ try { TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer serializer= factory.newTransformer(); serializer.setOutputProperty(Output...
@Test public void testFormatXmlInvalid() { PrintStream origErr = System.err; try { // The parser will print an error, so let it go where we will not see it System.setErr(new PrintStream(new OutputStream() { @Override public void write(int b) th...
public static long doubleHashCode(double value) { // canonicalize +0 and -0 to a single value value = value == -0 ? 0 : value; // doubleToLongBits converts all NaNs to the same representation return AbstractLongType.hash(doubleToLongBits(value)); }
@Test public void testDoubleHashCode() { assertEquals(doubleHashCode(0), doubleHashCode(Double.parseDouble("-0"))); //0x7ff8123412341234L is a different representation of NaN assertEquals(doubleHashCode(Double.NaN), doubleHashCode(longBitsToDouble(0x7ff8123412341234L))); }
public <T> Serializer<T> getSerializer(Class<T> c) { Serialization<T> serializer = getSerialization(c); if (serializer != null) { return serializer.getSerializer(c); } return null; }
@Test public void testGetSerializer() { // Test that a valid serializer class is returned when its present assertNotNull("A valid class must be returned for default Writable SerDe", factory.getSerializer(Writable.class)); // Test that a null is returned when none can be found. assertNull("A nu...
public FileIO getFileIO(StorageType.Type storageType) throws IllegalArgumentException { Supplier<? extends RuntimeException> exceptionSupplier = () -> new IllegalArgumentException(storageType.getValue() + " is not configured"); if (HDFS.equals(storageType)) { return Optional.ofNullable(hdfsFileIO)...
@Test public void testGetLocalFileIO() { // local storage is configured Assertions.assertNotNull(fileIOManager.getFileIO(StorageType.LOCAL)); }
@Udf(description = "Converts a string representation of a date in the given format" + " into a DATE value.") public Date parseDate( @UdfParameter( description = "The string representation of a date.") final String formattedDate, @UdfParameter( description = "The format pattern sh...
@Test public void shouldConvertYearMonthToDate() { // When: final Date result = udf.parseDate("2021-12", "yyyy-MM"); // Then: assertThat(result.getTime(), is(1638316800000L)); }
public boolean setNewAssignee(DefaultIssue issue, @Nullable UserIdDto userId, IssueChangeContext context) { if (userId == null) { return false; } checkState(issue.assignee() == null, "It's not possible to update the assignee with this method, please use assign()"); issue.setFieldChange(context, AS...
@Test void set_new_assignee() { boolean updated = underTest.setNewAssignee(issue, new UserIdDto("user_uuid", "user_login"), context); assertThat(updated).isTrue(); assertThat(issue.assignee()).isEqualTo("user_uuid"); assertThat(issue.assigneeLogin()).isEqualTo("user_login"); assertThat(issue.mustS...
@Override public synchronized T getValue(int index) { BarSeries series = getBarSeries(); if (series == null) { // Series is null; the indicator doesn't need cache. // (e.g. simple computation of the value) // --> Calculating the value T result = calcul...
@Test // should be not null public void getValueWithNullBarSeries() { ConstantIndicator<Num> constant = new ConstantIndicator<>( new BaseBarSeriesBuilder().withNumTypeOf(numFunction).build(), numFunction.apply(10)); assertEquals(numFunction.apply(10), constant.getValue(0)); ...
public T getResult() { return result; }
@Test public void testEthSyncingInProgress() { buildResponse( "{\n" + " \"id\":1,\n" + " \"jsonrpc\": \"2.0\",\n" + " \"result\": {\n" + " \"startingBlock\": \"0x384\",\n" ...
@SuppressWarnings("unchecked") public static void validateFormat(Object offsetData) { if (offsetData == null) return; if (!(offsetData instanceof Map)) throw new DataException("Offsets must be specified as a Map"); validateFormat((Map<Object, Object>) offsetData); ...
@Test public void testValidateFormatMapWithNonStringKeys() { Map<Object, Object> offsetData = new HashMap<>(); offsetData.put("k1", "v1"); offsetData.put(1, "v2"); DataException e = assertThrows(DataException.class, () -> OffsetUtils.validateFormat(offsetData)); assertThat(e....
public static boolean containsObject(Object obj) { if (obj == null) { return false; } // get object set Set<Object> objectSet = OBJECT_SET_LOCAL.get(); if (objectSet.isEmpty()) { return false; } return objectSet.contains(getUniqueSubstitu...
@Test public void testContainsObject() { Assertions.assertFalse(CycleDependencyHandler.containsObject(null)); }
Future<Boolean> canRollController(int nodeId) { LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId); return describeMetadataQuorum().map(info -> { boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info); if (!canRoll) { ...
@Test public void shouldTestDynamicTimeoutValue(VertxTestContext context) { Map<Integer, OptionalLong> controllers = new HashMap<>(); controllers.put(1, OptionalLong.of(10000L)); controllers.put(2, OptionalLong.of(9950L)); // Edge case close to the timeout Admin admin = setUpMocks(1,...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test public void testNotParenAnd() { final Predicate parsed = PredicateExpressionParser.parse("!(com.linkedin.data.it.AlwaysTruePredicate & com.linkedin.data.it.AlwaysFalsePredicate)"); Assert.assertEquals(parsed.getClass(), NotPredicate.class); final Predicate intermediate = ((NotPredicate) parsed).g...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsAtLeast_primitiveFloatArray_success() { assertThat(array(1.1f, TOLERABLE_2POINT2, 3.3f)) .usingTolerance(DEFAULT_TOLERANCE) .containsAtLeast(array(2.2f, 1.1f)); }
public static ValueLabel formatPacketRate(long packets) { return new ValueLabel(packets, PACKETS_UNIT).perSec(); }
@Test public void formatPacketRateKilo2() { vl = TopoUtils.formatPacketRate(1034); assertEquals(AM_WL, "1.01 Kpps", vl.toString()); }
public static String toSQL(ParseNode statement) { return new AST2SQLBuilderVisitor(false, false, true).visit(statement); }
@Test public void testInsertFromFiles() { String sql = "insert into t0 (v1, v2)" + "select * from files('path' = 's3://xxx/zzz', 'format' = 'parquet', 'aws.s3.access_key' = 'ghi', " + "'aws.s3.secret_key' = 'jkl', 'aws.s3.region' = 'us-west-1')"; StatementBase stmt = ...
static List<ClassLoader> selectClassLoaders(ClassLoader classLoader) { // list prevents reordering! List<ClassLoader> classLoaders = new ArrayList<>(); if (classLoader != null) { classLoaders.add(classLoader); } // check if TCCL is same as given classLoader ...
@Test public void selectingSameTcclAndGivenClassLoader() { ClassLoader same = new URLClassLoader(new URL[0]); Thread currentThread = Thread.currentThread(); ClassLoader tccl = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(same); List<ClassLoader>...