focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> children = new AttributedList<>(); String page = null; do { final TeamDriveList list = sessi...
@Test public void list() throws Exception { final AttributedList<Path> list = new DriveTeamDrivesListService(session, new DriveFileIdProvider(session)).list( DriveHomeFinderService.SHARED_DRIVES_NAME, new DisabledListProgressListener()); assertNotSame(AttributedList.emptyList(), list); ...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { if (readerWay.hasTag("hazmat:adr_tunnel_cat", TUNNEL_CATEGORY_NAMES)) { HazmatTunnel code = HazmatTunnel.valueOf(readerWay.getTag("hazmat:adr_tunnel_cat")); hazT...
@Test public void testHazmatSubtags() { EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; ReaderWay readerWay = new ReaderWay(1); readerWay.setTag("tunnel", "yes"); readerWay.setTag("hazmat:A", "no"); parser.handleWayTags(edgeId, edgeIntAccess, ...
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { if (!(statement.getStatement() instanceof CreateSource) && !(statement.getStatement() instanceof CreateAsSelect)) { return statement; } t...
@Test public void shouldThrowIfCsasKeyTableElementsNotCompatibleExtraKey() { // Given: givenFormatsAndProps("protobuf", null, ImmutableMap.of("KEY_SCHEMA_ID", new IntegerLiteral(42))); givenDDLSchemaAndFormats(LOGICAL_SCHEMA_EXTRA_KEY, "protobuf", "avro", SerdeFeature.WRAP_SINGLES, SerdeFe...
@ExceptionHandler(RuntimeException.class) protected ResponseEntity<?> handleRuntimeException(final RuntimeException runtimeException) { CustomError customError = CustomError.builder() .httpStatus(HttpStatus.NOT_FOUND) .header(CustomError.Header.API_ERROR.getName()) ...
@Test void givenRuntimeException_whenHandleRuntimeException_thenRespondWithNotFound() { // Given RuntimeException ex = new RuntimeException("Runtime exception message"); CustomError expectedError = CustomError.builder() .httpStatus(HttpStatus.NOT_FOUND) .hea...
public static void executeEmbeddedDump(Runnable runnable) { DUMP_EXECUTOR.execute(runnable); }
@Test void testExecuteEmbeddedDump() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); Runnable runnable = atomicInteger::incrementAndGet; PersistenceExecutor.executeEmbeddedDump(runnable); TimeUnit.MILLISECONDS.sleep...
public void putUserProperty(final String name, final String value) { if (MessageConst.STRING_HASH_SET.contains(name)) { throw new RuntimeException(String.format( "The Property<%s> is used by system, input another please", name)); } if (value == null || value.trim().i...
@Test public void putUserProperty() throws Exception { Message m = new Message(); m.putUserProperty("prop1", "val1"); Assert.assertEquals("val1", m.getUserProperty("prop1")); }
@Override public void createSubnet(Subnet osSubnet) { checkNotNull(osSubnet, ERR_NULL_SUBNET); checkArgument(!Strings.isNullOrEmpty(osSubnet.getId()), ERR_NULL_SUBNET_ID); checkArgument(!Strings.isNullOrEmpty(osSubnet.getNetworkId()), ERR_NULL_SUBNET_NET_ID); checkArgument(!Strings.i...
@Test(expected = IllegalArgumentException.class) public void testCreateSubnetWithNullCidr() { final Subnet testSubnet = NeutronSubnet.builder() .networkId(NETWORK_ID) .build(); testSubnet.setId(SUBNET_ID); target.createSubnet(testSubnet); }
@Override public void writeFloat(final float v) throws IOException { writeInt(Float.floatToIntBits(v)); }
@Test public void testWriteFloatForPositionV() throws Exception { float v = 1.1f; out.writeFloat(1, v); int expected = Float.floatToIntBits(v); int actual = Bits.readIntB(out.buffer, 1); assertEquals(actual, expected); }
protected BigDecimal convertDecimal(Object value, DecimalType type) { BigDecimal bigDecimal; if (value instanceof BigDecimal) { bigDecimal = (BigDecimal) value; } else if (value instanceof Number) { Number num = (Number) value; Double dbl = num.doubleValue(); if (dbl.equals(Math.floo...
@Test public void testDecimalConversion() { Table table = mock(Table.class); when(table.schema()).thenReturn(SIMPLE_SCHEMA); RecordConverter converter = new RecordConverter(table, config); BigDecimal expected = new BigDecimal("123.45"); ImmutableList.of("123.45", 123.45d, expected) .for...
public static void createTopics( Logger log, String bootstrapServers, Map<String, String> commonClientConf, Map<String, String> adminClientConf, Map<String, NewTopic> topics, boolean failOnExisting) throws Throwable { // this method wraps the call to createTopics() that takes admin clien...
@Test public void testCreateNonExistingTopicsWithZeroTopicsDoesNothing() throws Throwable { WorkerUtils.createTopics( log, adminClient, Collections.emptyMap(), false); assertEquals(0, adminClient.listTopics().names().get().size()); }
void resetTimeouts() { update(time.milliseconds()); sessionTimer.reset(rebalanceConfig.sessionTimeoutMs); pollTimer.reset(maxPollIntervalMs); heartbeatTimer.reset(rebalanceConfig.heartbeatIntervalMs); }
@Test public void testResetTimeouts() { time.sleep(maxPollIntervalMs); assertTrue(heartbeat.sessionTimeoutExpired(time.milliseconds())); assertEquals(0, heartbeat.timeToNextHeartbeat(time.milliseconds())); assertTrue(heartbeat.pollTimeoutExpired(time.milliseconds())); heartb...
@Override public boolean deleteService(String serviceName) throws NacosException { return deleteService(serviceName, Constants.DEFAULT_GROUP); }
@Test void testDeleteService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; //when nacosNamingMaintainService.deleteService(serviceName, groupName); //then verify(serverProxy, times(1)).deleteService(service...
public Node parse() throws ScanException { return E(); }
@Test public void empty() { try { Parser<Object> p = new Parser(""); p.parse(); fail(""); } catch (ScanException e) { } }
public Struct(Schema schema) { if (schema.type() != Schema.Type.STRUCT) throw new DataException("Not a struct schema: " + schema); this.schema = schema; this.values = new Object[schema.fields().size()]; }
@Test public void testValidateStructWithNullValue() { Schema schema = SchemaBuilder.struct() .field("one", Schema.STRING_SCHEMA) .field("two", Schema.STRING_SCHEMA) .field("three", Schema.STRING_SCHEMA) .build(); Struct struct = new St...
List<DataflowPackage> stageClasspathElements( Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) { return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions); }
@Test public void testPackageUploadWithFileSucceeds() throws Exception { Pipe pipe = Pipe.open(); String contents = "This is a test!"; File tmpFile = makeFileWithContents("file.txt", contents); when(mockGcsUtil.getObjects(anyListOf(GcsPath.class))) .thenReturn( ImmutableList.of( ...
@Override public Meter meter(String name) { return NoopMeter.INSTANCE; }
@Test public void accessingACustomMeterRegistersAndReusesIt() { final MetricRegistry.MetricSupplier<Meter> supplier = () -> meter; final Meter meter1 = registry.meter("thing", supplier); final Meter meter2 = registry.meter("thing", supplier); assertThat(meter1).isExactlyInstanceOf(N...
@Override public LoggingConfiguration getConfiguration(final Path file) throws BackgroundException { final Path bucket = containerService.getContainer(file); if(bucket.isRoot()) { return LoggingConfiguration.empty(); } try { final Storage.Buckets.Get request =...
@Test public void testGetConfiguration() throws Exception { final GoogleStorageLoggingFeature feature = new GoogleStorageLoggingFeature(session); final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); feature.setConfiguration(bucket, new Logging...
@Deprecated public String javaUnbox(Schema schema) { return javaUnbox(schema, false); }
@Test void javaUnbox() throws Exception { SpecificCompiler compiler = createCompiler(); compiler.setEnableDecimalLogicalType(false); Schema intSchema = Schema.create(Schema.Type.INT); Schema longSchema = Schema.create(Schema.Type.LONG); Schema floatSchema = Schema.create(Schema.Type.FLOAT); S...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testBagIsEmptyAfterClear() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); bag.clear(); ReadableState<Boolean> result = bag.isEmpty(); Mockito.verify(mockReader, never()) ...
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test public void shouldGetIntSchemaForIntegerClass() { assertThat( UdfUtil.getSchemaFromType(Integer.class), equalTo(ParamTypes.INTEGER) ); }
@Override public void write(final int b) throws IOException { throw new IOException(new UnsupportedOperationException()); }
@Test public void testSmallChunksToWrite() throws Exception { final CryptoVault vault = this.getVault(); final ByteArrayOutputStream cipherText = new ByteArrayOutputStream(); final FileHeader header = vault.getFileHeaderCryptor().create(); final CryptoOutputStream stream = new Crypto...
@Override public int compareTo(COSObjectKey other) { return Long.compare(numberAndGeneration, other.numberAndGeneration); }
@Test void compareToInputNotNullOutputNotNull() { // Arrange final COSObjectKey objectUnderTest = new COSObjectKey(1L, 0); final COSObjectKey other = new COSObjectKey(9_999_999L, 0); // Act final int retvalNegative = objectUnderTest.compareTo(other); final int re...
public static String format(CharSequence template, Map<?, ?> map) { return format(template, map, true); }
@Test public void formatTest() { final String template = "你好,我是{name},我的电话是:{phone}"; final String result = StrUtil.format(template, Dict.create().set("name", "张三").set("phone", "13888881111")); assertEquals("你好,我是张三,我的电话是:13888881111", result); final String result2 = StrUtil.format(template, Dict.create().se...
@Override public void commitAfterRecovery() throws IOException { LOGGER.trace( "Committing recoverable after recovery with options {}: {}", options, recoverable); // see discussion: https://github.com/apache/flink/pull/15599#discussion_r623127365 // only write the final blob...
@Test public void commitWithRecoveryOverwriteShouldSucceedTest() throws IOException { blobStorage.createBlob(blobIdentifier); GSRecoverableWriterCommitter committer = commitTestInternal(); committer.commitAfterRecovery(); }
@Override public void eventReceived(Action action, Pod pod) { logger.debug( "Received {} event for pod {}, details: {}{}", action, pod.getMetadata().getName(), System.lineSeparator(), KubernetesUtils.tryToGetPrettyPrintYaml(pod....
@Test void testCallbackHandler() { FlinkPod pod = new FlinkPod.Builder().build(); final KubernetesPodsWatcher podsWatcher = new KubernetesPodsWatcher( TestingWatchCallbackHandler.<KubernetesPod>builder() .setOnAddedConsumer(pods...
public static Serializer getSerializer(String alias) { // 工厂模式 托管给ExtensionLoader return EXTENSION_LOADER.getExtension(alias); }
@Test public void getSerializer1() { Serializer serializer = SerializerFactory.getSerializer("test"); Assert.assertNotNull(serializer); Assert.assertEquals(TestSerializer.class, serializer.getClass()); }
public int quarter() { return month() / 3 + 1; }
@Test public void quarterTest() { DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT); Quarter quarter = dateTime.quarterEnum(); assertEquals(Quarter.Q1, quarter); dateTime = new DateTime("2017-04-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT); quarter = dateTime.quart...
@Override @SuppressWarnings("unchecked") public void onApplicationEvent(@NotNull final DataChangedEvent event) { for (DataChangedListener listener : listeners) { if ((!(listener instanceof AbstractDataChangedListener)) && clusterProperties.isEnabled() ...
@Test public void onApplicationEventWithMetaDataConfigGroupTest() { when(clusterProperties.isEnabled()).thenReturn(true); when(shenyuClusterSelectMasterService.isMaster()).thenReturn(true); ConfigGroupEnum configGroupEnum = ConfigGroupEnum.META_DATA; DataChangedEvent dataChangedEvent...
public boolean shouldLog(final Logger logger, final String path, final int responseCode) { if (rateLimitersByPath.containsKey(path)) { final RateLimiter rateLimiter = rateLimitersByPath.get(path); if (!rateLimiter.tryAcquire()) { if (pathLimitHit.tryAcquire()) { logger.info("Hit rate l...
@Test public void shouldSkipRateLimited_responseCode() { // Given: when(rateLimiter.tryAcquire()).thenReturn(true, false, false, false); when(rateLimiter.getRate()).thenReturn(1d); // When: assertThat(loggingRateLimiter.shouldLog(logger, "/foo", RESPONSE_CODE), is(true)); assertThat(loggingRa...
public String toString(String name) { return toString(name, ""); }
@Test public void testToString_String() { System.out.println("toString"); String expResult; String result; Properties props = new Properties(); props.put("value1", "sTr1"); props.put("value2", "str_2"); props.put("empty", ""); props.put("str", "abc");...
Record deserialize(Object data) { return (Record) fieldDeserializer.value(data); }
@Test public void testStructDeserialize() { Deserializer deserializer = new Deserializer.Builder() .schema(CUSTOMER_SCHEMA) .writerInspector((StructObjectInspector) IcebergObjectInspector.create(CUSTOMER_SCHEMA)) .sourceInspector(CUSTOMER_OBJECT_INSPECTOR) .build(); Record exp...
@Override public long position() throws IOException { checkOpen(); long pos; synchronized (this) { boolean completed = false; try { begin(); // don't call beginBlocking() because this method doesn't block if (!isOpen()) { return 0; // AsynchronousCloseException will...
@Test public void testPositionNegative() throws IOException { FileChannel channel = channel(regularFile(0), READ, WRITE); try { channel.position(-1); fail(); } catch (IllegalArgumentException expected) { } }
@Override public AwsProxyResponse handle(Throwable ex) { log.error("Called exception handler for:", ex); // adding a print stack trace in case we have no appender or we are running inside SAM local, where need the // output to go to the stderr. ex.printStackTrace(); if (ex i...
@Test void streamHandle_InvalidRequestEventException_jsonContentTypeHeader() throws IOException { ByteArrayOutputStream respStream = new ByteArrayOutputStream(); exceptionHandler.handle(new InvalidRequestEventException(INVALID_REQUEST_MESSAGE, null), respStream); assertNotNull(r...
public static LocalDate parseDate(CharSequence text) { return parseDate(text, (DateTimeFormatter) null); }
@Test public void parseSingleMonthAndDayTest() { final LocalDate localDate = LocalDateTimeUtil.parseDate("2020-1-1", "yyyy-M-d"); assertEquals("2020-01-01", localDate.toString()); }
@Override public Optional<String> getContentHash() { return Optional.ofNullable(mContentHash); }
@Test public void writeByteArrayForLargeFile() throws Exception { int partSize = (int) FormatUtils.parseSpaceSize(PARTITION_SIZE); byte[] b = new byte[partSize + 1]; assertEquals(mStream.getPartNumber(), 1); mStream.write(b, 0, b.length); assertEquals(mStream.getPartNumber(), 2); Mockito.verif...
public static String buildSelectorRealPath(final String pluginName, final String selectorId) { return String.join(PATH_SEPARATOR, SELECTOR_PARENT, pluginName, selectorId); }
@Test public void testBuildSelectorRealPath() { String pluginName = RandomStringUtils.randomAlphanumeric(10); String selectorId = RandomStringUtils.randomAlphanumeric(10); String selectorRealPath = DefaultPathConstants.buildSelectorRealPath(pluginName, selectorId); assertThat(selecto...
@Override public Space get() throws BackgroundException { try { final EueApiClient client = new EueApiClient(session); final UserInfoApi userInfoApi = new UserInfoApi(client); final UserInfoResponseModel userInfoResponseModel = userInfoApi.userinfoGet(null, null); ...
@Test public void testGetQuota() throws Exception { final Quota.Space quota = new EueQuotaFeature(session).get(); assertNotNull(quota.available); assertNotNull(quota.used); assertNotEquals(0L, quota.available, 0L); assertNotEquals(0L, quota.used, 0L); assertTrue(quota...
public Optional<String> branch() { return configuration.get(BRANCH_NAME); }
@Test public void should_define_branch_name() { settings.setProperty("sonar.branch.name", "name"); assertThat(underTest.branch()).isEqualTo(Optional.of("name")); }
@VisibleForTesting boolean hasApplication(ApplicationId appId) { return collectorManager.containsTimelineCollector(appId); }
@Test void testAddApplication() throws Exception { auxService = createCollectorAndAddApplication(); // auxService should have a single app assertTrue(auxService.hasApplication(appAttemptId.getApplicationId())); auxService.close(); }
ConnectorStatus.Listener wrapStatusListener(ConnectorStatus.Listener delegateListener) { return new ConnectorStatusListener(delegateListener); }
@Test public void testConnectorFailureBeforeStartupRecordedMetrics() { WorkerMetricsGroup workerMetricsGroup = new WorkerMetricsGroup(new HashMap<>(), new HashMap<>(), connectMetrics); final ConnectorStatus.Listener connectorListener = workerMetricsGroup.wrapStatusListener(delegateConnectorListener)...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldThrowOnNoElementsInCreateStream() { // Given: final CreateStream statement = new CreateStream(SOME_NAME, TableElements.of(), false, true, withProperties, false); // When: final Exception e = assertThrows( KsqlException.class, () -> createSourceFactory.c...
public static Collection<PValue> nonAdditionalInputs(AppliedPTransform<?, ?, ?> application) { ImmutableList.Builder<PValue> mainInputs = ImmutableList.builder(); PTransform<?, ?> transform = application.getTransform(); for (Map.Entry<TupleTag<?>, PCollection<?>> input : application.getInputs().entrySet()) ...
@Test public void nonAdditionalInputsWithAdditionalInputsSucceeds() { Map<TupleTag<?>, PValue> additionalInputs = new HashMap<>(); additionalInputs.put(new TupleTag<String>() {}, pipeline.apply(Create.of("1, 2", "3"))); additionalInputs.put(new TupleTag<Long>() {}, pipeline.apply(GenerateSequence.from(3L)...
@Override public void onAdd(Request request) { if (isDisposed()) { return; } queue.addImmediately(request); }
@Test void shouldNotAddExtensionWhenAddPredicateAlwaysFalse() { var type = GroupVersionKind.fromAPIVersionAndKind("v1alpha1", "User"); when(matchers.onAddMatcher()).thenReturn( DefaultExtensionMatcher.builder(client, type).build()); watcher.onAdd(createFake("fake-name")); ...
public Map<String, String> getPropertiesWithPrefix(String prefix) { return getPropertiesWithPrefix(prefix, false); }
@Test public void testGetPropertiesWithPrefixEmptyResult() { ConfigurationProperties configurationProperties = new ConfigurationProperties(PROPERTIES); Map<String, String> propsEmptyPrefix = configurationProperties.getPropertiesWithPrefix(""); Map<String, String> propsLongPrefix = configurationPr...
@Override public void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException { NamingUtils.batchCheckInstanceIsLegal(instances); batchCheckAndStripGroupNamePrefix(instances, groupName); clientProxy.batchRegisterService(serviceN...
@Test void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; int port = 10000; instance.setServiceName("WrongGroup" + "@@" + serviceName); instance.se...
boolean sendRecords() { int processed = 0; recordBatch(toSend.size()); final SourceRecordWriteCounter counter = toSend.isEmpty() ? null : new SourceRecordWriteCounter(toSend.size(), sourceTaskMetricsGroup); for (final SourceRecord preTransformRecord : toSend) { ...
@Test public void testSendRecordsTopicCreateRetries() { createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECO...
@Override public boolean hasSameTypeAs(Task task) { if (!getClass().equals(task.getClass())) { return false; } return this.pluginConfiguration.equals(((PluggableTask) task).pluginConfiguration); }
@Test public void shouldReturnTrueWhenPluginConfigurationForTwoPluggableTasksIsExactlyTheSame() { PluginConfiguration pluginConfiguration = new PluginConfiguration("test-plugin-1", "1.0"); PluggableTask pluggableTask1 = new PluggableTask(pluginConfiguration, new Configuration()); PluggableTa...
@Override public Column convert(BasicTypeDefine typeDefine) { try { return super.convert(typeDefine); } catch (SeaTunnelRuntimeException e) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefi...
@Test public void testConvertDouble() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("float8") .dataType("float8") .build(); Column column = Kin...
@Override public boolean retryRequest(HttpResponse response, int executionCount, HttpContext ctx) { log.fine(() -> String.format("retryRequest(responseCode='%s', executionCount='%d', ctx='%s'", response.getStatusLine().getStatusCode(), executionCount, ctx)); Http...
@Test void retries_for_listed_exceptions_until_max_retries_exceeded() { int maxRetries = 2; DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder .withFixedDelay(Duration.ofSeconds(2), maxRetries) .retryForStatusCodes(List.of(HttpStatus....
@Override public HttpRestResult<String> httpPost(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception { final long endTime = System.currentTimeMillis() + readTimeoutMs; String currentServerAddr = serverListMgr.getC...
@Test void testHttpPostSuccess() throws Exception { when(nacosRestTemplate.<String>postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTT...
public Optional<YamlRuleConfiguration> swapToYamlRuleConfiguration(final Collection<RepositoryTuple> repositoryTuples, final Class<? extends YamlRuleConfiguration> toBeSwappedType) { RepositoryTupleEntity tupleEntity = toBeSwappedType.getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) ...
@Test void assertSwapToYamlRuleConfigurationWithGlobalLeafYamlRuleConfiguration() { Optional<YamlRuleConfiguration> actual = new RepositoryTupleSwapperEngine().swapToYamlRuleConfiguration( Collections.singleton(new RepositoryTuple("/rules/leaf/versions/0", "value: foo")), GlobalLeafYamlRuleC...
public static AuditActor system(@Nonnull NodeId nodeId) { return new AutoValue_AuditActor(URN_GRAYLOG_NODE + requireNonNull(nodeId, "nodeId must not be null").getNodeId()); }
@Test public void testSystem() { final NodeId nodeId = new SimpleNodeId("28164cbe-4ad9-4c9c-a76e-088655aa78892"); final AuditActor actor = AuditActor.system(nodeId); assertThat(actor.urn()).isEqualTo("urn:graylog:node:28164cbe-4ad9-4c9c-a76e-088655aa78892"); }
public String getName() { return name; }
@Test public void testGetName() { // Create an ExceptionEvent with a code ExceptionEvent exceptionEvent = new ExceptionEvent("CODE123"); // Test the getName method assertEquals("CODE123", exceptionEvent.getName()); }
@Override public @Nullable Boolean trySample(@Nullable M method) { if (method == null) return null; Sampler sampler = methodToSamplers.get(method); if (sampler == NULL_SENTINEL) return null; if (sampler != null) return sampler.isSampled(0L); // counting sampler ignores the input sampler = samplerOf...
@Test void cardinalityIsPerAnnotationNotInvocation() { Traced traced = traced(1.0f, 0, true); declarativeSampler.trySample(traced); declarativeSampler.trySample(traced); declarativeSampler.trySample(traced); assertThat(declarativeSampler.methodToSamplers) .hasSize(1); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testOrderedListAddBeforeRangeRead() throws Exception { StateTag<OrderedListState<String>> addr = StateTags.orderedList("orderedList", StringUtf8Coder.of()); OrderedListState<String> orderedList = underTest.state(NAMESPACE, addr); SettableFuture<Iterable<TimestampedValue<String>>...
@Override public List<URL> lookup(URL url) { List<URL> result = new ArrayList<>(); Map<String, List<URL>> notifiedUrls = getNotified().get(url); if (CollectionUtils.isNotEmptyMap(notifiedUrls)) { for (List<URL> urls : notifiedUrls.values()) { for (URL u : urls) { ...
@Test void lookupTest() { // loop up before registry try { abstractRegistry.lookup(null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } List<URL> urlList1 = abstractRegistry.lookup(te...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { Map<String, Object> fields = new HashMap<>(); if (flatten) { final String json = new String(rawMessage.getPayload(), charset); try { fields = flatten(json); } catch (Js...
@Test public void testReadResultingInSingleStringFullJson() throws Exception { RawMessage json = new RawMessage("{\"url\":\"https://api.github.com/repos/Graylog2/graylog2-server/releases/assets/22660\",\"download_count\":76185,\"id\":22660,\"name\":\"graylog2-server-0.20.0-preview.1.tgz\",\"label\":\"graylo...
@Override public Map<String, NoteInfo> list(AuthenticationInfo subject) throws IOException { // Must to create rootNotebookFileObject each time when call method list, otherwise we can not // get the updated data under this folder. this.rootNotebookFileObject = fsManager.resolveFile(this.rootNotebookFolder...
@Test void testSkipInvalidDirectoryName() throws IOException { createNewDirectory(".hidden_dir"); createNewNote("{}", "hidden_note", "my_project/.hidden_dir/note"); Map<String, NoteInfo> noteInfos = notebookRepo.list(AuthenticationInfo.ANONYMOUS); assertEquals(0, noteInfos.size()); }
@Override public Collection<Long> generateKeys(final AlgorithmSQLContext context, final int keyGenerateCount) { Collection<Long> result = new LinkedList<>(); for (int index = 0; index < keyGenerateCount; index++) { result.add(generateKey()); } return result; }
@Test void assertMaxTolerateTimeDifferenceMillisecondsWhenNegative() { assertThrows(AlgorithmInitializationException.class, () -> TypedSPILoader.getService(KeyGenerateAlgorithm.class, "SNOWFLAKE", PropertiesBuilder.build(new Property("max-tolerate-time-difference-milliseconds", "-1"))) ...
@Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final LifecycleConfiguration that = (LifecycleConfiguration) o; if(!Objects.equals(expiration, that.e...
@Test public void testEquals() { assertEquals(LifecycleConfiguration.empty(), new LifecycleConfiguration()); assertEquals(new LifecycleConfiguration(1, 1), new LifecycleConfiguration(1, 1)); assertEquals(new LifecycleConfiguration(1, 2), new LifecycleConfiguration(1, 2)); assertNotEq...
@VisibleForTesting static List<TopicPartition> getAllTopicPartitions( SerializableFunction<Map<String, Object>, Consumer<byte[], byte[]>> kafkaConsumerFactoryFn, Map<String, Object> kafkaConsumerConfig, Set<String> topics, @Nullable Pattern topicPattern) { List<TopicPartition> current = ne...
@Test public void testGetAllTopicPartitionsWithGivenPattern() throws Exception { Consumer<byte[], byte[]> mockConsumer = Mockito.mock(Consumer.class); when(mockConsumer.listTopics()) .thenReturn( ImmutableMap.of( "topic1", ImmutableList.of( ...
@Scheduled(initialDelay = 5000, fixedDelay = 15000) private void reload() { try { Page<RoleInfo> roleInfoPage = rolePersistService.getRolesByUserNameAndRoleName(StringUtils.EMPTY, StringUtils.EMPTY, DEFAULT_PAGE_NO, Integer.MAX_VALUE); if (roleInfoPage == null) { ...
@Test void reload() throws Exception { Method reload = nacosRoleServiceClass.getDeclaredMethod("reload"); reload.setAccessible(true); reload.invoke(nacosRoleService); }
public static Schema getBeamSchemaFromProtoSchema(String schemaString, String messageName) { Descriptors.Descriptor descriptor = getDescriptorFromProtoSchema(schemaString, messageName); return ProtoDynamicMessageSchema.forDescriptor(ProtoDomain.buildFrom(descriptor), descriptor) .getSchema(); }
@Test public void testProtoSchemaWitPackageStringToBeamSchema() { Schema schema = ProtoByteUtils.getBeamSchemaFromProtoSchema( PROTO_STRING_PACKAGE_SCHEMA, "com.test.proto.MyMessage"); Assert.assertEquals(schema.getFieldNames(), SCHEMA.getFieldNames()); }
public List<GetBucketListReply.BucketInfo> retrieveBucketList(BucketId bucketId, String bucketSpace) throws BucketStatsException { GetBucketListMessage msg = new GetBucketListMessage(bucketId, bucketSpace); GetBucketListReply bucketListReply = sendMessage(msg, GetBucketListReply.class); return b...
@Test void testRoute() throws BucketStatsException { String route = "default"; BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId("id:ns:type::another")); GetBucketListReply reply = new GetBucketListReply(); reply.getBuckets().add(new GetBucketListReply.BucketInfo(bucketI...
@NonNull @Override public ConnectionFileName toPvfsFileName( @NonNull FileName providerFileName, @NonNull T details ) throws KettleException { // Determine the part of provider file name following the connection "root". // Use the transformer to generate the connection root provider uri. // Both uri...
@Test public void testToPvfsFileNameHandlesTheConnectionRoot() throws Exception { // Example: SMB with root path mockDetailsWithDomain( details1, "my-domain:8080" ); when( details1.hasBuckets() ).thenReturn( true ); mockDetailsWithRootPath( details1, "my/root/path" ); String connectionRootProvid...
public static String captchaNumber(int length) { StringBuilder sb = new StringBuilder(); Random rand = new Random(); for (int i = 0; i < length; i++) { sb.append(rand.nextInt(10)); } return sb.toString(); }
@Test public void testCaptchaNumber() throws Exception { Assert.assertEquals(0, UUID.captchaNumber(0).length()); Assert.assertEquals(2, UUID.captchaNumber(2).length()); Assert.assertEquals(4, UUID.captchaNumber(4).length()); Assert.assertEquals(10, UUID.captchaNumber(10).length()); ...
@Override public long computePullFromWhereWithException(MessageQueue mq) throws MQClientException { long result = -1; final ConsumeFromWhere consumeFromWhere = this.defaultMQPushConsumerImpl.getDefaultMQPushConsumer().getConsumeFromWhere(); final OffsetStore offsetStore = this.defaultMQPushC...
@Test public void testComputePullFromWhereWithException_eq_minus1_timestamp() throws MQClientException { when(offsetStore.readOffset(any(MessageQueue.class), any(ReadOffsetType.class))).thenReturn(-1L); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_TIMESTAMP); when(admin.searchO...
@Operation(summary = "Receive app to app SAML AuthnRequest") @PostMapping(value = {"/frontchannel/saml/v4/entrance/request_authentication", "/frontchannel/saml/v4/idp/request_authentication"}, produces = "application/json", consumes = "application/x-www-form-urlencoded", params = "Type") @ResponseBody publi...
@Test public void requestAuthenticationAppTest() throws DienstencatalogusException, ComponentInitializationException, SamlSessionException, AdException, SamlValidationException, SharedServiceClientException, MessageDecodingException { Map<String, Object> authenticationParameters = new HashMap<>(); a...
public Map<String, String> pukRequestAllowed(PukRequest request) throws PukRequestException { final PenRequestStatus result = repository.findFirstByBsnAndDocTypeAndSequenceNoOrderByRequestDatetimeDesc(request.getBsn(), request.getDocType(), request.getSequenceNo()); checkExpirationDatePen(result); ...
@Test public void pukRequestAllowedIsAllowedWithin21Days() throws PukRequestException { // set valid date of penrequest in repo status.setPinResetValidDate(LocalDateTime.of(2019, 1, 2, 12, 33)); Map<String, String> result = service.pukRequestAllowed(request); assertEquals("OK", res...
public Hamlet(PrintWriter out, int nestLevel, boolean wasInline) { super(out, nestLevel, wasInline); }
@Test void testHamlet() { Hamlet h = newHamlet(). title("test"). h1("heading 1"). p("#id.class"). b("hello"). em("world!").__(). div("#footer"). __("Brought to you by"). a("https://hostname/", "Somebody").__(); PrintWriter out = h.getWriter(); ...
@Override public CompletionStage<Boolean> putIfAbsentAsync(K key, V value) { return cache.putIfAbsentAsync(key, value); }
@Test public void testPutIfAbsentAsync() throws Exception { cache.put(42, "oldValue"); assertTrue(adapter.putIfAbsentAsync(23, "newValue").toCompletableFuture().get()); assertFalse(adapter.putIfAbsentAsync(42, "newValue").toCompletableFuture().get()); assertEquals("newValue", cache...
public boolean add(final Integer element) { return addInt(null == element ? nullValue : element); }
@Test void shouldEqualGenericList() { final int count = 7; final List<Integer> genericList = new ArrayList<>(); for (int i = 0; i < count; i++) { list.add(i); genericList.add(i); } list.add(null); genericList.add(null); a...
public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); }
@Test public void uploadFileTest() { Long petId = null; String additionalMetadata = null; File file = null; ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); // TODO: test validations }
@Override public boolean sendElectionMessage(int currentId, String content) { var candidateList = findElectionCandidateInstanceList(currentId); if (candidateList.isEmpty()) { return true; } else { var electionMessage = new Message(MessageType.ELECTION_INVOKE, ""); candidateList.forEach((...
@Test void testElectionMessageAccepted() { var instance1 = new BullyInstance(null, 1, 1); var instance2 = new BullyInstance(null, 1, 2); var instance3 = new BullyInstance(null, 1, 3); var instance4 = new BullyInstance(null, 1, 4); Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instan...
public static <T> Optional<T> quietlyEval(String action, String path, CallableRaisingIOE<T> operation) { try { return Optional.of(once(action, path, operation)); } catch (Exception e) { LOG.debug("Action {} failed", action, e); return Optional.empty(); } }
@Test public void testQuietlyEvalReturnValueFail() { // use a variable so IDEs don't warn of numeric overflows int d = 0; assertOptionalUnset("quietly", quietlyEval("", "", () -> 3 / d)); }
@Udf public <T extends Comparable<? super T>> List<T> arraySortDefault(@UdfParameter( description = "The array to sort") final List<T> input) { return arraySortWithDirection(input, "ASC"); }
@Test public void shouldReturnNullForNullInput() { assertThat(udf.arraySortDefault((List<String>) null), is(nullValue())); }
List<String> getRandomWords() { return Arrays.asList(words); }
@Test public void testRandomTextDataGeneratorUniqueness() { RandomTextDataGenerator rtdg1 = new RandomTextDataGenerator(10, 1L, 5); Set<String> words1 = new HashSet(rtdg1.getRandomWords()); RandomTextDataGenerator rtdg2 = new RandomTextDataGenerator(10, 0L, 5); Set<String> words2 = new HashSet(rtdg2....
public double sphericalDistance(LatLong other) { return LatLongUtils.sphericalDistance(this, other); }
@Test public void sphericalDistance_originToIslaGenovesa_returnQuarterOfEarthEquatorCircumference() { // This is the origin of the WGS-84 reference system LatLong zeroZero = new LatLong(0d, 0d); // These coordinates are 1/4 Earth circumference from zero on the equator LatLong islaGen...
@SuppressWarnings("unchecked") @VisibleForTesting void handleNMContainerStatus(NMContainerStatus containerStatus, NodeId nodeId) { ApplicationAttemptId appAttemptId = containerStatus.getContainerId().getApplicationAttemptId(); RMApp rmApp = rmContext.getRMApps().get(appAttemptId.getApplicati...
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testHandleContainerStatusInvalidCompletions() throws Exception { rm = new MockRM(new YarnConfiguration()); rm.start(); EventHandler handler = spy(rm.getRMContext().getDispatcher().getEventHandler()); // Case 1: Unmanaged AM ...
@Override public Object structuralValue(Void value) { return STRUCTURAL_VOID_VALUE; }
@Test public void testStructuralValueSharesSameObject() { assertEquals(TEST_CODER.structuralValue(null), TEST_CODER.structuralValue(null)); // This is a minor performance optimization to not encode and compare empty byte // arrays. assertSame(TEST_CODER.structuralValue(null), TEST_CODER.structuralValu...
@Override protected LocalResourceId matchNewResource(String singleResourceSpec, boolean isDirectory) { if (isDirectory) { if (!singleResourceSpec.endsWith(File.separator)) { singleResourceSpec += File.separator; } } else { checkArgument( !singleResourceSpec.endsWith(File.se...
@Test public void testMatchNewResource() { // TODO: Java core test failing on windows, https://github.com/apache/beam/issues/20461 assumeFalse(SystemUtils.IS_OS_WINDOWS); LocalResourceId fileResource = localFileSystem.matchNewResource("/some/test/resource/path", false /* isDirectory */); Local...
public static File getFile(String fileName) { String extension = fileName.substring(fileName.lastIndexOf('.') + 1); File toReturn = ResourceHelper.getFileResourcesByExtension(extension) .stream() .filter(file -> file.getName().equals(fileName)) .findFirst(...
@Test public void getFileNotExistingDirectory() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> FileUtils.getFile(TEST_FILE, NOT_EXISTING_DIRECTORY)); }
@Override public Object getInternalProperty(String key) { return System.getProperty(key); }
@Test void testGetSysProperty() { Assertions.assertNull(sysConfig.getInternalProperty(MOCK_KEY)); Assertions.assertFalse(sysConfig.containsKey(MOCK_KEY)); Assertions.assertNull(sysConfig.getString(MOCK_KEY)); Assertions.assertNull(sysConfig.getProperty(MOCK_KEY)); System.setP...
@Override @Nullable @GuardedBy("getLock()") public PageInfo evict(CacheScope scope, PageStoreDir pageStoreDir) { return evictInternal(pageStoreDir.getEvictor()); }
@Test public void evict() throws Exception { mMetaStore.addPage(mPage, mPageInfo); assertEquals(mPageInfo, mMetaStore.evict(mPageStoreDir)); mMetaStore.removePage(mPageInfo.getPageId()); Assert.assertNull(mMetaStore.evict(mPageStoreDir)); assertEquals(0, mCachedPageGauge.getValue()); }
@Override public <T extends Serializable> T getCachedValue(String idempotentId) throws IllegalArgumentException { if (!knownValues.containsKey(idempotentId)) { throw new IllegalArgumentException( idempotentId + " is not a known key, known keys: " + Joiner.on(", ")...
@Test public void getCachedValue() throws Exception { googleExecutor.setJobId(JOB_ID); googleExecutor.executeAndSwallowIOExceptions("id1", ITEM_NAME, () -> "idempotentId1"); assertEquals(googleExecutor.getCachedValue("id1"), "idempotentId1"); }
static ObjectName newObjectName(String name) { try { return new ObjectName(name); } catch (MalformedObjectNameException e) { String msg = "Illegal ObjectName: " + name; throw new CacheException(msg, e); } }
@Test public void newObjectName_malformed() { assertThrows(CacheException.class, () -> JmxRegistration.newObjectName("a=b")); }
public boolean isEmpty() { return events.isEmpty(); }
@Test public void testIsEmpty() { assertFalse(batchEventData.isEmpty()); assertFalse(batchEventDataSameAttribute.isEmpty()); assertFalse(batchEventDataOtherSource.isEmpty()); assertFalse(batchEventDataOtherPartitionId.isEmpty()); assertFalse(batchEventDataOtherEvent.isEmpty()...
public static void write8ByteUnsignedIntLittleEndian(long data, ByteArrayOutputStream out) { out.write((byte) (data & 0xFF)); out.write((byte) (data >>> 8)); out.write((byte) (data >>> 16)); out.write((byte) (data >>> 24)); out.write((byte) (data >>> 32)); out.write((byte...
@Test public void testWrite8ByteUnsignedIntLittleEndian() { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteHelper.write8ByteUnsignedIntLittleEndian(72_340_168_547_287_295L, out); Assert.assertArrayEquals(new byte[] {-1, -64, 64, 1, 0, 1, 1, 1}, out.toByteArray()); }
public static String decompressZlib(byte[] compressedData) throws IOException { return decompressZlib(compressedData, Long.MAX_VALUE); }
@Test public void testDecompressZlibBomb() throws URISyntaxException, IOException { final URL url = Resources.getResource("org/graylog2/plugin/zlib64mb.raw"); final byte[] testData = Files.readAllBytes(Paths.get(url.toURI())); assertThat(Tools.decompressZlib(testData, 1024)).hasSize(1024); ...
@Override public int compare(Collection<? extends Comparable<T>> one, Collection<? extends Comparable<T>> other) { return comparator.compare(string(one), string(other)); }
@Test public void shouldCompareSortedCollections() { AlphaAsciiCollectionComparator<Foo> comparator = new AlphaAsciiCollectionComparator<>(); assertThat(comparator.compare(List.of(new Foo("foo"), new Foo("quux")), List.of(new Foo("foo"), new Foo("bar"))), greaterThan(0)); assertThat(comparat...
List<CSVResult> sniff(Reader reader) throws IOException { if (!reader.markSupported()) { reader = new BufferedReader(reader); } List<CSVResult> ret = new ArrayList<>(); for (char delimiter : delimiters) { reader.mark(markLimit); try { C...
@Test public void testCSVBasic() throws Exception { List<CSVResult> results = sniff(DELIMITERS, CSV_BASIC, StandardCharsets.UTF_8); assertEquals(4, results.size()); assertEquals(Character.valueOf(','), results.get(0).getDelimiter()); results = sniff(DELIMITERS, CSV_BASIC2, StandardC...
public String getCatalog() { return catalog; }
@Test public void testGetDefaultSessionCatalog() { UserProperty userProperty = new UserProperty(); String defaultSessionCatalog = userProperty.getCatalog(); Assert.assertEquals(InternalCatalog.DEFAULT_INTERNAL_CATALOG_NAME, defaultSessionCatalog); }
@Override public boolean isPasswordConfigurable() { // Only provide account email return false; }
@Test public void testPassword() { assertFalse(new DriveProtocol().isPasswordConfigurable()); }
@VisibleForTesting StandardContext addStaticDir(Tomcat tomcat, String contextPath, File dir) { try { fs.createOrCleanupDir(dir); } catch (IOException e) { throw new IllegalStateException(format("Fail to create or clean-up directory %s", dir.getAbsolutePath()), e); } return addContext(tomc...
@Test public void cleanup_static_directory_if_already_exists() throws Exception { File dir = temp.newFolder(); FileUtils.touch(new File(dir, "foo.txt")); underTest.addStaticDir(tomcat, "/deploy", dir); assertThat(dir).isDirectory() .exists() .isEmptyDirectory(); }
@Override public void recordLoadFailure(long loadTime) { loadFailure.update(loadTime, TimeUnit.NANOSECONDS); totalLoadTime.add(loadTime); }
@Test public void loadFailure() { stats.recordLoadFailure(256); assertThat(registry.timer(PREFIX + ".loads-failure").getCount()).isEqualTo(1); }
public void cancelLike() { if (this.likesCount > 0) { this.likesCount--; } }
@Test void review_공감수가_0이라면_공감수를_감소하지_않는다() { // given Review review = Review.builder().likesCount(0).build(); // when review.cancelLike(); // then assertEquals(review.getLikesCount(), 0); }
@Override public void run() { try { backgroundJobServer.getJobSteward().notifyThreadOccupied(); MDCMapper.loadMDCContextFromJob(job); performJob(); } catch (Exception e) { if (isJobDeletedWhileProcessing(e)) { // nothing to do anymore a...
@Test void onStartIfJobIsProcessingByStorageProviderItStaysInProcessingAndThenSucceeded() throws Exception { Job job = anEnqueuedJob() .withProcessingState(backgroundJobServer.getConfiguration().getId()) .build(); mockBackgroundJobRunner(job, jobFromStorage -> { ...
public static List<String> split( String str, char delim ) { return split( str, delim, false, false ); }
@Test void splitTrimAndExcludeEmpty() { // empty assertEquals( Arrays.asList(), StringUtils.split( "", ',', true, true ) ); // not empty assertEquals( Arrays.asList( "a" ), StringUtils.split( "a", ',', true, true ) ); assertEquals( Arrays.asList( "a", "b" ), StringUtils.split( "a,b", ',', ...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetchMaxPollRecordsUnaligned() { final int maxPollRecords = 2; buildFetcher(maxPollRecords); Set<TopicPartition> tps = new HashSet<>(); tps.add(tp0); tps.add(tp1); assignFromUser(tps); subscriptions.seek(tp0, 1); subscriptions.se...
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull26() { // Arrange final int type = 24; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Update_rows_v1", actual); }