focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@SuppressWarnings({"unchecked", "UnstableApiUsage"}) @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement) { if (!(statement.getStatement() instanceof DropStatement)) { return statement; } final DropStatement dropStatement = (DropState...
@Test public void shouldDeleteValueAvroSchemaInSrEvenIfKeyDeleteFails() throws IOException, RestClientException { // Given: when(topic.getKeyFormat()).thenReturn(KeyFormat.of(FormatInfo.of(FormatFactory.AVRO.name()), SerdeFeatures.of(), Optional.empty())); when(topic.getValueFormat()).thenReturn(ValueForm...
private ExitStatus run() { try { init(); return new Processor().processNamespace().getExitStatus(); } catch (IllegalArgumentException e) { System.out.println(e + ". Exiting ..."); return ExitStatus.ILLEGAL_ARGUMENTS; } catch (IOException e) { System.out.println(e + ". Exiting...
@Test(timeout = 300000) public void testMoveWhenStoragePolicySatisfierIsRunning() throws Exception { final Configuration conf = new HdfsConfiguration(); conf.set(DFSConfigKeys.DFS_STORAGE_POLICY_SATISFIER_MODE_KEY, StoragePolicySatisfierMode.EXTERNAL.toString()); final MiniDFSCluster cluster = new...
protected void validatePersistentTopicName(String property, String namespace, String encodedTopic) { validateTopicName(property, namespace, encodedTopic); if (topicName.getDomain() != TopicDomain.persistent) { throw new RestException(Status.NOT_ACCEPTABLE, "Need to provide a persistent topic...
@Test public void testValidatePersistentTopicNameInvalid() { String tenant = "test-tenant"; String namespace = "test-namespace"; String topic = Codec.encode("test-topic"); AdminResource nPResource = mockNonPersistentResource(); try { nPResource.validatePersistent...
public static MetricsSource makeSource(Object source) { return new MetricsSourceBuilder(source, DefaultMetricsFactory.getAnnotatedMetricsFactory()).build(); }
@Test public void testClasses() { MetricsRecordBuilder rb = getMetrics( MetricsAnnotations.makeSource(new MyMetrics3())); MetricsCollector collector = rb.parent(); verify(collector).addRecord(info("MyMetrics3", "My metrics")); verify(rb).add(tag(MsInfo.Context, "foo")); }
public static void main(String[] args) { BarSeries series = CsvTradesLoader.loadBitstampSeries(); System.out.println("Series: " + series.getName() + " (" + series.getSeriesPeriodDescription() + ")"); System.out.println("Number of bars: " + series.getBarCount()); System.out.println("Firs...
@Test public void test() { CsvTradesLoader.main(null); }
@Override public void write(int b) throws IOException { if (buffer.length <= bufferIdx) { flushInternalBuffer(); } buffer[bufferIdx] = (byte) b; ++bufferIdx; }
@Test void testPrimaryWriteFail() throws Exception { DuplicatingCheckpointOutputStream duplicatingStream = createDuplicatingStreamWithFailingPrimary(); testFailingPrimaryStream( duplicatingStream, () -> { for (int i = 0; i < 128; i+...
public static KeyFormat sanitizeKeyFormat( final KeyFormat keyFormat, final List<SqlType> newKeyColumnSqlTypes, final boolean allowKeyFormatChangeToSupportNewKeySchema ) { return sanitizeKeyFormatWrapping( !allowKeyFormatChangeToSupportNewKeySchema ? keyFormat : sanitizeKeyFormat...
@Test public void shouldNotConvertFormatForMulticolKeysWhenSanitizingIfDisallowed() { // Given: final KeyFormat format = KeyFormat.nonWindowed( FormatInfo.of(KafkaFormat.NAME), SerdeFeatures.of()); // When: final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyFormat(format, MUL...
public static Map<String, String> resolveAll(Map<String, String> properties) { return resolveAll(System.getenv(), properties); }
@Test public void testMultipleEnvironmentSubstitutions() { Map<String, String> result = EnvironmentUtil.resolveAll( ImmutableMap.of("USER", "u", "VAR", "value"), ImmutableMap.of("user-test", "env:USER", "other", "left-alone", "var", "env:VAR")); assertThat(result) .as(...
public static <E> List<E> ensureImmutable(List<E> list) { if (list.isEmpty()) return Collections.emptyList(); // Faster to make a copy than check the type to see if it is already a singleton list if (list.size() == 1) return Collections.singletonList(list.get(0)); if (isImmutable(list)) return list; ...
@Test void ensureImmutable_returnsImmutableEmptyList() { assertThrows(UnsupportedOperationException.class, () -> { Lists.ensureImmutable(new ArrayList<>()).add("foo"); }); }
@VisibleForTesting static boolean onlyContainsSpecifiersInAllowList(String pattern) { var noSpecifierFormatBase = SPECIFIER_ALLOW_LIST_REGEX.matcher(pattern).replaceAll(""); // If it still has a specifier after the replacement, it means that it was not on the allowlist. return !noSpecifierFormatBase.conta...
@Test public void testOnlyContainsSpecifiersInAllowList() { assertTrue(onlyContainsSpecifiersInAllowList("%%%n%b%h%c%s")); assertTrue(onlyContainsSpecifiersInAllowList("%1$s%<s%1s%1.2s%2$-3.4s%<-42s")); // Implies a Formattable argument, so no need to match here assertFalse(onlyContainsSpecifiersInAll...
@Override public Path resolvePath(final Path p) throws IOException { return super.resolvePath(fullPath(p)); }
@Test public void testResolvePath() throws IOException { Assert.assertEquals(chrootedTo, fSys.resolvePath(new Path("/"))); fileSystemTestHelper.createFile(fSys, "/foo"); Assert.assertEquals(new Path(chrootedTo, "foo"), fSys.resolvePath(new Path("/foo"))); }
public void schedule(String eventDefinitionId) { final EventDefinitionDto eventDefinition = getEventDefinitionOrThrowIAE(eventDefinitionId); createJobDefinitionAndTriggerIfScheduledType(eventDefinition); }
@Test @MongoDBFixtures("event-processors-without-schedule.json") public void scheduleWithMissingEventDefinition() { final String id = "54e3deadbeefdeadbeef9999"; // The event definition should not exist so our test works assertThat(eventDefinitionService.get(id)).isNotPresent(); ...
public static void warn(final Logger logger, final String format, final Supplier<Object> supplier) { if (logger.isWarnEnabled()) { logger.warn(format, supplier.get()); } }
@Test public void testNeverWarn() { when(logger.isWarnEnabled()).thenReturn(false); LogUtils.warn(logger, supplier); verify(supplier, never()).get(); }
@Override public FullBinaryMemcacheResponse replace(ByteBuf content) { ByteBuf key = key(); if (key != null) { key = key.retainedDuplicate(); } ByteBuf extras = extras(); if (extras != null) { extras = extras.retainedDuplicate(); } retu...
@Test public void fullReplace() { ByteBuf newContent = Unpooled.copiedBuffer("new value", CharsetUtil.UTF_8); FullBinaryMemcacheResponse newInstance = response.replace(newContent); try { assertResponseEquals(response, newContent, newInstance); } finally { resp...
@Override public void write(int value) { bos.write(value); }
@Test public void serializeByteArrayWithLengthExceedingWithZeros() throws IOException { assertArrayEquals(new byte[] {1, 2}, write( (o) -> o.write(new byte[] { 0, 0, 1, 2}, 2))); }
public static <V> SetOnceReference<V> of(final V value) { return new SetOnceReference<>(Objects.requireNonNull(value)); }
@Test public void testFromOfWithValue() { final Sentinel sentinel = new Sentinel(); checkSetReferenceIsImmutable(SetOnceReference.of(sentinel), sentinel); }
public Collection<Task> createTasks(final Consumer<byte[], byte[]> consumer, final Map<TaskId, Set<TopicPartition>> tasksToBeCreated) { final List<Task> createdTasks = new ArrayList<>(); for (final Map.Entry<TaskId, Set<TopicPartition>> newTaskAndPartitions : tas...
@Test public void shouldThrowStreamsExceptionOnErrorCloseThreadProducerIfEosDisabled() { createTasks(); mockClientSupplier.producers.get(0).closeException = new RuntimeException("KABOOM!"); final StreamsException thrown = assertThrows( StreamsException.class, activeT...
public static Collection<SubquerySegment> getSubquerySegments(final SelectStatement selectStatement) { List<SubquerySegment> result = new LinkedList<>(); extractSubquerySegments(result, selectStatement); return result; }
@Test void assertGetSubquerySegmentsWithMultiNestedSubquery() { SelectStatement selectStatement = mock(SelectStatement.class); SubquerySegment subquerySelect = createSubquerySegmentForFrom(); when(selectStatement.getFrom()).thenReturn(Optional.of(new SubqueryTableSegment(0, 0, subquerySelect...
@Override public long get(long key) { return super.get0(key, 0); }
@Test public void testGet() { final long key = random.nextLong(); final long valueAddress = insert(key).address(); final long valueAddress2 = hsa.get(key); assertEquals(valueAddress, valueAddress2); }
@Override public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) { return isSimpleType(type); }
@Test void testAccept() { assertTrue(builder.accept(processingEnv, vField.asType())); assertTrue(builder.accept(processingEnv, zField.asType())); assertTrue(builder.accept(processingEnv, cField.asType())); assertTrue(builder.accept(processingEnv, bField.asType())); assertTrue...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuilder buf = new StringBuilder(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STATE: handleLiteralState(...
@Test public void literalEndingWithDollar_LOGBACK_1149() throws ScanException { String input = "a$"; Tokenizer tokenizer = new Tokenizer(input); List<Token> tokenList = tokenizer.tokenize(); witnessList.add(new Token(Token.Type.LITERAL, "a")); witnessList.add(new Token(Token.Type.LITERAL, "$")); ...
public static void setGlobalSampler(final String sampler) { if (StringUtils.isNotBlank(sampler)) { try { globalSampler = CountSampler.create(sampler); } catch (Exception e) { globalSampler = Sampler.ALWAYS_SAMPLE; } } }
@Test public void testSetGlobalSampler() throws NoSuchFieldException, IllegalAccessException { LogCollectConfigUtils.setGlobalSampler("1"); Field field = LogCollectConfigUtils.class.getDeclaredField("globalSampler"); field.setAccessible(true); assertEquals(field.get("const"), Sampler...
public static AwsCredentialsProvider deserializeAwsCredentialsProvider( String serializedCredentialsProvider) { return deserialize(serializedCredentialsProvider, AwsCredentialsProvider.class); }
@Test(expected = IllegalArgumentException.class) public void testFailOnAwsCredentialsProviderDeserialization() { AwsSerializableUtils.deserializeAwsCredentialsProvider("invalid string"); }
public void readDataFromInputStream( InputStream is ) throws KettleException { // Clear the information // clear(); if ( log.isBasic() ) { log.logBasic( BaseMessages.getString( PKG, "RepositoryMeta.Log.ReadingXMLFile", "FromInputStream" ) ); } try { // Check and open XML document ...
@Test public void testErrorReadingInputStream() throws Exception { try { repoMeta.readDataFromInputStream( getClass().getResourceAsStream( "filedoesnotexist.xml" ) ); } catch ( KettleException e ) { assertEquals( Const.CR + "Error reading information from file:" + Const.CR + "Inpu...
@Override public Iterator<Map.Entry<String, Object>> iterator() { return map.entrySet().iterator(); }
@Test public void noProperties() { CamelMessagingHeadersExtractAdapter adapter = new CamelMessagingHeadersExtractAdapter(map, true); Iterator<Map.Entry<String, Object>> iterator = adapter.iterator(); assertFalse(iterator.hasNext()); }
@Override public void receivedEvent(Event event, Map<String, Object> metadata) { log.debug("received event {}, metadata {}", event, metadata); if (event instanceof ResourceEvent) { final ResourceAction action = ((ResourceEvent) event).getAction(); final Optional<Class<? extends BaseResource<?, ?, ...
@Test void testReceivedEvent() { Event event = new ResourceEvent(ResourceAction.ADDED, resourceId, buildNamespacedResource()); operatorMetrics.receivedEvent(event, metadata); Map<String, Metric> metrics = operatorMetrics.metricRegistry().getMetrics(); assertEquals(2, metrics.size()); assertTrue(me...
@SuppressWarnings("unchecked") private void publishContainerResumedEvent( ContainerEvent event) { if (publishNMContainerEvents) { ContainerResumeEvent resumeEvent = (ContainerResumeEvent) event; ContainerId containerId = resumeEvent.getContainerID(); ContainerEntity entity = createContaine...
@Test public void testPublishContainerResumedEvent() { ApplicationId appId = ApplicationId.newInstance(0, 1); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ContainerId cId = ContainerId.newContainerId(appAttemptId, 1); ContainerEvent containerEvent = ...
@Deprecated public static <T> Task<T> withSideEffect(final Task<T> parent, final Task<?> sideEffect) { return parent.withSideEffect(t -> sideEffect); }
@Test public void testSideEffectPartialCompletion() throws InterruptedException { // ensure that the whole can finish before the individual side effect task finishes. Task<String> fastTask = new BaseTask<String>() { @Override protected Promise<? extends String> run(Context context) throws Exceptio...
public static DataType convertToDataType(String avroSchemaString) { return convertToDataType(avroSchemaString, true); }
@Test void testConvertAvroSchemaToDataType() { final String schema = User.getClassSchema().toString(true); validateUserSchema(AvroSchemaConverter.convertToDataType(schema)); }
public static HbaseSQLReaderConfig parseConfig(Configuration cfg) { return HbaseSQLReaderConfig.parse(cfg); }
@Test public void testParseConfig() { Configuration config = Configuration.from(jsonStr); HbaseSQLReaderConfig readerConfig = HbaseSQLHelper.parseConfig(config); System.out.println("tablenae = " +readerConfig.getTableName() +",zk = " +readerConfig.getZkUrl()); assertEquals("TABLE1", ...
@Override public CompletableFuture<Void> process() { return CompletableFuture.runAsync( () -> { try (WriteBatch writeBatch = new WriteBatch(batchRequest.size() * PER_RECORD_ESTIMATE_BYTES)) { for (ForStDBPutRequest<?, ?,...
@Test public void testValueStateWriteBatch() throws Exception { ForStValueState<Integer, VoidNamespace, String> valueState1 = buildForStValueState("test-write-batch-1"); ForStValueState<Integer, VoidNamespace, String> valueState2 = buildForStValueState("test-write-bat...
@Override public void start() { if (isDisabled()) { LOG.debug(MESSAGE_SCM_STEP_IS_DISABLED_BY_CONFIGURATION); return; } if (settings.hasKey(SCM_PROVIDER_KEY)) { settings.get(SCM_PROVIDER_KEY).ifPresent(this::setProviderIfSupported); } else { autodetection(); if (this.prov...
@Test void fail_when_considerOldScmUrl_finds_invalid_provider_in_link() { when(settings.get(ScannerProperties.LINKS_SOURCES_DEV)).thenReturn(Optional.of("scm:invalid")); assertThatThrownBy(() -> underTest.start()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no SCM provide...
@Override public void add(String field, String value, Map<String, String[]> data) { if (! include(field, value)) { return; } if (ALWAYS_SET_FIELDS.contains(field)) { setAlwaysInclude(field, value, data); return; } else if (ALWAYS_ADD_FIELDS.contain...
@Test public void testMetadataFactoryFieldsConfig() throws Exception { TikaConfig tikaConfig = new TikaConfig(TikaConfigTest.class.getResourceAsStream("TIKA-3695-fields.xml")); AutoDetectParserConfig config = tikaConfig.getAutoDetectParserConfig(); MetadataWriteFilterFactory ...
public FEELFnResult<Object> invoke(@ParameterName("list") List list) { if ( list == null || list.isEmpty() ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty")); } else { try { return FEELFnResult.ofResult(C...
@Test void invokeArrayWithHeterogenousTypes() { FunctionTestUtil.assertResultError(maxFunction.invoke(new Object[]{1, "test", BigDecimal.valueOf(10.2)}), InvalidParametersEvent.class); }
synchronized void add(int splitCount) { int pos = count % history.length; history[pos] = splitCount; count += 1; }
@Test public void testTwoMoreThanFullHistory() { EnumerationHistory history = new EnumerationHistory(3); history.add(1); history.add(2); history.add(3); history.add(4); history.add(5); int[] expectedHistorySnapshot = {3, 4, 5}; testHistory(history, expectedHistorySnapshot); }
public static CreateOptions defaults(AlluxioConfiguration conf) { return new CreateOptions(conf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK)); }
@Test public void defaults() throws IOException { CreateOptions options = CreateOptions.defaults(mConfiguration); assertFalse(options.getCreateParent()); assertFalse(options.isEnsureAtomic()); assertNull(options.getOwner()); assertNull(options.getGroup()); String umask = mConfiguration.getStr...
@Override public final short readShort() throws EOFException { short s = readShort(pos); pos += SHORT_SIZE_IN_BYTES; return s; }
@Test public void testReadShortByteOrder() throws Exception { short read = in.readShort(LITTLE_ENDIAN); short val = Bits.readShortL(INIT_DATA, 0); assertEquals(val, read); }
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // Initialize the encoder, decoder, flow controllers, and internal state. encoder.lifecycleManager(this); decoder.lifecycleManager(this); encoder.flowController().channelHandlerContext(ctx); deco...
@Test public void verifyChannelHandlerCanBeReusedInPipeline() throws Exception { when(connection.isServer()).thenReturn(true); handler = newHandler(); // Only read the connection preface...after preface is read internal state of Http2ConnectionHandler // is expected to change relativ...
@Override public Collection<String> getJdbcUrlPrefixes() { return Collections.singletonList(String.format("jdbc:%s:", getType().toLowerCase())); }
@Test void assertGetJdbcUrlPrefixes() { assertThat(TypedSPILoader.getService(DatabaseType.class, "Oracle").getJdbcUrlPrefixes(), is(Collections.singletonList("jdbc:oracle:"))); }
@Override public void onNext(final T next) { }
@Test public void onNext() { completeObserver.onNext(new Object()); }
@Override public AbstractByteBuf encode(Object object, Map<String, String> context) { CustomHessianSerializer serializer = getCustomSerializer(object); if (serializer != null) { return serializer.encodeObject(object, context); } else { UnsafeByteArrayOutputStream byt...
@Test public void encode() { AbstractByteBuf data = serializer.encode("xxx", null); String dst = (String) serializer.decode(data, String.class, null); Assert.assertEquals("xxx", dst); boolean error = false; try { serializer.decode(data, "", null); } catch...
public Node getLeader(String clusterName) { Map<String/*raft-group*/, Node> map = leaders.computeIfAbsent(clusterName, k -> new ConcurrentHashMap<>()); List<Node> nodes = new ArrayList<>(map.values()); return nodes.size() > 0 ? nodes.get(ThreadLocalRandom.current().nextInt(nodes.size())) : null;...
@Test public void testGetLeader() { Assertions.assertNull(metadata.getLeader("leader")); Node node = new Node(); node.setGroup("group"); metadata.setLeaderNode("leader", node); Assertions.assertNotNull(metadata.getLeader("leader")); }
String getCertificate() { return configuration.get(CERTIFICATE).orElseThrow(() -> new IllegalArgumentException("Identity provider certificate is missing")); }
@Test public void fail_to_get_certificate_when_null() { assertThatThrownBy(() -> underTest.getCertificate()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Identity provider certificate is missing"); }
public static <K> KStreamHolder<K> build( final KStreamHolder<K> stream, final StreamSelectKey<K> selectKey, final RuntimeBuildContext buildContext ) { return build(stream, selectKey, buildContext, PartitionByParamsFactory::build); }
@Test public void shouldOnlyMap() { // When: StreamSelectKeyBuilder .build(stream, selectKey, buildContext, paramBuilder); // Then: verify(kstream).map(any(), any()); verifyNoMoreInteractions(kstream, rekeyedKstream); }
public static String substringAfter(String s, String splitter) { final int indexOf = s.indexOf(splitter); return indexOf >= 0 ? s.substring(indexOf + splitter.length()) : null; }
@Test void testSubstringAfterSplitterSingleChar() { assertThat(substringAfter("15", "-")).isNull(); assertThat(substringAfter("15-ea", "-")).isEqualTo("ea"); }
@Override public Map<String, ScannerPlugin> installRequiredPlugins() { LOG.info("Loading required plugins"); InstallResult result = installPlugins(p -> p.getRequiredForLanguages() == null || p.getRequiredForLanguages().isEmpty()); LOG.debug("Plugins not loaded because they are optional: {}", result.skipp...
@Test public void reload_list_if_plugin_uninstalled_during_blue_green_switch() throws IOException { WsTestUtil.mockReader(wsClient, "api/plugins/installed", new InputStreamReader(getClass().getResourceAsStream("ScannerPluginInstallerTest/blue-installed.json")), new InputStreamReader(getClass().getReso...
public static PipelineOptions create() { return new Builder().as(PipelineOptions.class); }
@Test public void testOptionsIdIsSet() throws Exception { ObjectMapper mapper = new ObjectMapper() .registerModules(ObjectMapper.findModules(ReflectHelpers.findClassLoader())); PipelineOptions options = PipelineOptionsFactory.create(); // We purposely serialize/deserialize to get anoth...
@Override public NativeQuerySpec<Record> select(String sql, Object... args) { return new NativeQuerySpecImpl<>(this, sql, args, DefaultRecord::new, false); }
@Test public void testNative() { database.dml() .insert("s_test_event") .value("id", "helper_testNative") .value("name", "Ename2") .execute() .sync(); database.dml() .insert("s_test") .va...
@Override public String grantAccessRequestBody(List<SecurityAuthConfig> authConfigs, Map<String, String> authSessionContext) { Map<String, Object> requestMap = new HashMap<>(); requestMap.put("auth_configs", getAuthConfigs(authConfigs)); requestMap.put("auth_session", authSessionContext); ...
@Test void grantAccessRequestBodyTests() { String json = converter.grantAccessRequestBody(List.of(new SecurityAuthConfig("github", "cd.go.github", create("url", false, "some-url"))), Map.of("foo", "bar")); String expectedRequestBody = """ { "auth_configs": [ ...
public boolean shouldRecord() { return this.recordingLevel.shouldRecord(config.recordLevel().id); }
@Test public void testShouldRecordForDebugLevelSensor() { Sensor debugSensor = new Sensor(null, "debugSensor", null, INFO_CONFIG, Time.SYSTEM, 0, Sensor.RecordingLevel.DEBUG); assertFalse(debugSensor.shouldRecord()); debugSensor = new Sensor(null, "debugSensor", null, DEBUG_CONF...
@Override public void delete(String propertyKey) { checkPropertyKey(propertyKey); try (DbSession dbSession = dbClient.openSession(false)) { dbClient.internalPropertiesDao().delete(dbSession, propertyKey); dbSession.commit(); } }
@Test public void delete_shouldCallDaoAndDeleteProperty() { underTest.delete(SOME_KEY); verify(internalPropertiesDao).delete(dbSession, SOME_KEY); verify(dbSession).commit(); }
public static WindowStoreIterator<ValueAndTimestamp<GenericRow>> fetch( final ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> store, final GenericKey key, final Instant lower, final Instant upper ) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWi...
@Test public void shouldThrowException_InvalidStateStoreException() throws IllegalAccessException { when(provider.stores(any(), any())).thenReturn(ImmutableList.of(meteredWindowStore)); SERDES_FIELD.set(meteredWindowStore, serdes); when(serdes.rawKey(any())).thenReturn(BYTES); when(meteredWindowStore....
public static StatementExecutorResponse execute( final ConfiguredStatement<ListTypes> configuredStatement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final ImmutableMap.Builder<String, SchemaInfo> types = ...
@Test public void shouldListTypes() { // When: final Optional<KsqlEntity> entity = ListTypesExecutor.execute( ConfiguredStatement.of(PreparedStatement.of("statement", new ListTypes(Optional.empty())), SessionConfig.of(KSQL_CONFIG, ImmutableMap.of())), mock(SessionProperties.class),...
public boolean isDeleteSyncSupported() { return allDevicesHaveCapability(DeviceCapabilities::deleteSync); }
@Test void isDeleteSyncSupported() { assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), List.of(deleteSyncCapableDevice), "1234".getBytes(StandardCharsets.UTF_8)).isDeleteSyncSupported()); assertFalse(AccountsHelper.generateTestAccount("+1800555...
public void replaceData(int index, T newScesimData) { scesimData.set(index, newScesimData); }
@Test public void replaceData() { final Scenario replaced = model.getDataByIndex(3); final Scenario replacement = new Scenario(); model.replaceData(3, replacement); assertThat(model.scesimData).hasSize(SCENARIO_DATA).doesNotContain(replaced); assertThat(mode...
@Override public String toString() { return String.format("(%s, %s, %s)", classname, name, actions); }
@Test public void testToString() { Permission permission = new Permission("classname", "name", "actions"); assertEquals("(classname, name, actions)", permission.toString()); }
@Override public void deleteArticle(Long id) { // 校验存在 validateArticleExists(id); // 删除 articleMapper.deleteById(id); }
@Test public void testDeleteArticle_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> articleService.deleteArticle(id), ARTICLE_NOT_EXISTS); }
public static boolean isLegalColumn(String col) { int len = col.length(); for (int i = 0; i < len; i++) { char c = col.charAt(i); if (c == '_' || c == '$' || Character.isLetterOrDigit(c)) { continue; } return false; } retur...
@Test void testLegal(){ assertTrue(QueryHelperUtils.isLegalColumn("test_name")); assertFalse(QueryHelperUtils.isLegalColumn("test-name")); assertFalse(QueryHelperUtils.isLegalColumn("test\nname")); }
public static WorkflowInstanceAggregatedInfo computeAggregatedView( WorkflowInstance workflowInstance, boolean statusKnown) { if (workflowInstance == null) { // returning empty object since cannot access state of the current instance run return new WorkflowInstanceAggregatedInfo(); } Work...
@Test public void testAggregatedViewDoublePreviouslySucceeded() { WorkflowInstance run1 = getGenericWorkflowInstance( 1, WorkflowInstance.Status.SUCCEEDED, RunPolicy.START_FRESH_NEW_RUN, null); Workflow runtimeWorkflow = mock(Workflow.class); Map<String, StepRuntimeState> decodedOver...
static void urlEncode(String str, StringBuilder sb) { for (int idx = 0; idx < str.length(); ++idx) { char c = str.charAt(idx); if ('+' == c) { sb.append("%2B"); } else if ('%' == c) { sb.append("%25"); } else { sb.ap...
@Test void testUrlEncodeByPercent() { // Arrange final StringBuilder sb = new StringBuilder("??????"); // Act GroupKey2.urlEncode("%", sb); // Assert side effects assertNotNull(sb); assertEquals("??????%25", sb.toString()); }
@Override public V takeLast() throws InterruptedException { return commandExecutor.getInterrupted(takeLastAsync()); }
@Test public void testTakeLast() throws InterruptedException { RBlockingDeque<Integer> deque = redisson.getPriorityBlockingDeque("queue:take"); deque.add(1); deque.add(2); deque.add(3); deque.add(4); assertThat(deque.takeLast()).isEqualTo(4); assertThat(dequ...
@Override public void getConfig(CloudTokenDataPlaneFilterConfig.Builder builder) { var clientsCfg = clients.stream() .filter(c -> !c.tokens().isEmpty()) .map(x -> new CloudTokenDataPlaneFilterConfig.Clients.Builder() .id(x.id()) ...
@Test void generates_correct_config_for_tokens() throws IOException { var certFile = securityFolder.resolve("foo.pem"); var clusterElem = DomBuilderTest.parse(servicesXmlTemplate.formatted(applicationFolder.toPath().relativize(certFile).toString())); createCertificate(certFile); buil...
@Override public SubClusterId getHomeSubcluster( ApplicationSubmissionContext appSubmissionContext, List<SubClusterId> blackListSubClusters) throws YarnException { // null checks and default-queue behavior validate(appSubmissionContext); List<ResourceRequest> rrList = appSubmissionCo...
@Test public void testMultipleResourceRequests() throws YarnException { List<ResourceRequest> requests = new ArrayList<ResourceRequest>(); requests.add(ResourceRequest .newInstance(Priority.UNDEFINED, "node1", Resource.newInstance(10, 1), 1)); requests.add(ResourceRequest .newI...
static LinkedHashMap<String, KiePMMLProbabilityConfidence> evaluateProbabilityConfidenceMap(final List<KiePMMLScoreDistribution> kiePMMLScoreDistributions, final double missingValuePenalty) { LinkedHashMap<String, Ki...
@Test void evaluateProbabilityConfidenceMap() { List<KiePMMLScoreDistribution> kiePMMLScoreDistributions = getRandomKiePMMLScoreDistributions(false); int totalRecordCount = kiePMMLScoreDistributions.stream() .map(KiePMMLScoreDistribution::getRecordCount) .reduce(0, In...
public static Collection<File> getFileResourcesByExtension(String extension) { return Arrays.stream(getClassPathElements()) .flatMap(elem -> internalGetFileResources(elem, Pattern.compile(".*\\." + extension + "$")) .stream()) .collect(Collectors.toSet());...
@Test public void getResourcesByExtensionExisting() { final Collection<File> retrieved = getFileResourcesByExtension("txt"); commonVerifyCollectionWithExpectedFile(retrieved, TEST_FILE); }
public static PathOutputCommitterFactory getCommitterFactory( Path outputPath, Configuration conf) { // determine which key to look up the overall one or a schema-specific // key LOG.debug("Looking for committer factory for path {}", outputPath); String key = COMMITTER_FACTORY_CLASS; if ...
@Test public void testCommitterFactoryUnknown() throws Throwable { Configuration conf = new Configuration(); // set the factory to an unknown class conf.set(COMMITTER_FACTORY_CLASS, "unknown"); intercept(RuntimeException.class, () -> getCommitterFactory(HDFS_PATH, conf)); }
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testMatchEachContainsDeep() { run( "def response = [ { a: 1, arr: [ { b: 2, c: 3 }, { b: 4, c: 5 } ] } ]", "match each response contains deep { a: 1, arr: [ { b: '#number', c: 3 } ] }" ); }
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { if (stream == null) { throw new NullPointerException("null stream"); } Throwable t; boolean alive =...
@Test public void testToFileHandler() throws Exception { //test that a server-side write-to-file works without proxying back the //AbstractContentHandlerFactory Path target = Files.createTempFile(tempDir, "fork-to-file-handler-", ".txt"); try (InputStream is = getResourceAsStream("/t...
@Override public void route(final RouteContext routeContext, final SingleRule singleRule) { if (routeContext.getRouteUnits().isEmpty() || sqlStatement instanceof SelectStatement) { routeStatement(routeContext, singleRule); } else { RouteContext newRouteContext = new RouteCont...
@Test void assertRouteWithDefaultSingleRule() throws SQLException { SingleStandardRouteEngine engine = new SingleStandardRouteEngine(mockQualifiedTables(), new MySQLCreateTableStatement(false)); SingleRule singleRule = new SingleRule(new SingleRuleConfiguration(Collections.emptyList(...
public int getSize() { return barSeries.getBarCount() - 1; }
@Test public void returnSize() { for (Returns.ReturnType type : Returns.ReturnType.values()) { // No return at index 0 BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d, 3d, 4d, 5d); Returns returns = new Returns(sampleBarSeries, new BaseTradingRecord(), t...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(containerService.isContainer(folder)) { final Storage.Buckets.Insert request = session.getClient().buckets().insert(session.getHost().getCredentials().getUsername(), ...
@Test public void testDirectoryWhitespace() throws Exception { final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new GoogleStorageDirectoryFeature(session).mkdir(new Path(bucket, String.format("%s %s", new Alphanum...
protected CertPair refreshCert() throws IOException { KeyPair keyPair = signWithEcdsa(); if (keyPair == null) { keyPair = signWithRsa(); } if (keyPair == null) { logger.error( CONFIG_SSL_CERT_GENERATE_FAILED, "", ...
@Test void testRefreshCert() throws IOException { try (MockedStatic<DubboCertManager> managerMock = Mockito.mockStatic(DubboCertManager.class, CALLS_REAL_METHODS)) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertManager certManager = new DubboCertMana...
TopicFilter topicFilter() { return getConfiguredInstance(TOPIC_FILTER_CLASS, TopicFilter.class); }
@Test public void testTopicMatching() { MirrorSourceConfig config = new MirrorSourceConfig(makeProps("topics", "topic1")); assertTrue(config.topicFilter().shouldReplicateTopic("topic1"), "topic1 replication property configuration failed"); assertFalse(config.topicFilter().sho...
public static Date parseDate(final String str) { try { return new Date(TimeUnit.DAYS.toMillis( LocalDate.parse(PartialStringToTimestampParser.completeDate(str)) .toEpochDay())); } catch (DateTimeParseException e) { throw new KsqlException("Failed to parse date '" + str ...
@Test public void shouldNotParseDate() { // When: final KsqlException e = assertThrows( KsqlException.class, () -> SqlTimeTypes.parseDate("foo") ); // Then assertThat(e.getMessage(), containsString( "Required format is: \"yyyy-MM-dd\"")); }
public static Boolean convertToBoolean(Schema schema, Object value) throws DataException { if (value == null) { return null; } else if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { SchemaAndValue parsed = parseStrin...
@Test public void shouldFailToParseInvalidBooleanValueString() { assertThrows(DataException.class, () -> Values.convertToBoolean(Schema.STRING_SCHEMA, "\"green\"")); }
public Set<Device> getDevicesFromPath(String path) throws IOException { MutableInt counter = new MutableInt(0); try (Stream<Path> stream = Files.walk(Paths.get(path), 1)) { return stream.filter(p -> p.toFile().getName().startsWith("veslot")) .map(p -> toDevice(p, counter)) .collect...
@Test public void testDeviceNumberFromMajorAndMinor() throws IOException { createVeSlotFile(0); createVeSlotFile(1); createVeSlotFile(2); createOsStateFile(0); when(mockCommandExecutor.getOutput()).thenReturn( "10:1:character special file", "1d:2:character special file", "4...
public static ProfileManager getInstance() { if (INSTANCE == null) { INSTANCE = new ProfileManager(); } return INSTANCE; }
@Test public void testSingleton() { ProfileManager instance1 = ProfileManager.getInstance(); ProfileManager instance2 = ProfileManager.getInstance(); assertSame(instance1, instance2, "ProfileManager should be singleton"); }
public boolean createTable(CreateTableStmt stmt, List<Column> partitionColumns) throws DdlException { String dbName = stmt.getDbName(); String tableName = stmt.getTableName(); Map<String, String> properties = stmt.getProperties() != null ? stmt.getProperties() : new HashMap<>(); Path tab...
@Test public void testCreateTable() throws DdlException { new MockUp<HiveWriteUtils>() { public void createDirectory(Path path, Configuration conf) { } }; HiveMetastoreOperations mockedHmsOps = new HiveMetastoreOperations(cachingHiveMetastore, true, n...
@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 shouldReturnStatementUnchangedIfCtFormatsDoNotSupportInference() { // Given: givenNeitherKeyNorValueInferenceSupported(); // When: final ConfiguredStatement<?> result = injector.inject(ctStatement); // Then: assertThat(result, is(sameInstance(ctStatement))); }
public void add(int value) { add(Util.toUnsignedLong(value)); }
@Test public void testEqual() { // empty == empty BitmapValue emp1 = new BitmapValue(); BitmapValue emp2 = new BitmapValue(); assertEquals(emp1, emp2); // empty == single value emp2.add(1); Assert.assertNotEquals(emp1, emp2); // empty == bitmap ...
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator204() { String[] schemes = {"http", "https"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); }
protected Name getReverseZoneName(Configuration conf) { Name name = null; String zoneSubnet = getZoneSubnet(conf); if (zoneSubnet == null) { LOG.warn("Zone subnet is not configured. Reverse lookups disabled"); } else { // is there a netmask String mask = conf.get(KEY_DNS_ZONE_MASK); ...
@Test public void testReverseZoneNames() throws Exception { Configuration conf = new Configuration(); conf.set(KEY_DNS_ZONE_SUBNET, "172.26.32.0"); conf.set(KEY_DNS_ZONE_MASK, "255.255.224.0"); Name name = getRegistryDNS().getReverseZoneName(conf); assertEquals("wrong name", "26.172.in-addr.arpa....
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) { return containsAtLeastEntriesIn(accumulateMultimap(k0, v0, rest)); }
@Test public void containsAtLeastVarargInOrder() { ImmutableMultimap<Integer, String> actual = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); assertThat(actual).containsAtLeast(3, "one", 3, "six", 4, "five", 4, "four").inOrder(); }
public static LocalDateTime parse(CharSequence text) { return parse(text, (DateTimeFormatter) null); }
@Test public void parseTest3() { final LocalDateTime localDateTime = LocalDateTimeUtil.parse("12:23:56", DatePattern.NORM_TIME_PATTERN); assertEquals("12:23:56", Objects.requireNonNull(localDateTime).toLocalTime().toString()); }
@Override public ObjectiveTranslation doTranslate(NextObjective obj) throws FabricPipelinerException { final ObjectiveTranslation.Builder resultBuilder = ObjectiveTranslation.builder(); switch (obj.type()) { case SIMPLE: simpleNext(obj, resul...
@Test public void testXconnectOutput() throws FabricPipelinerException { TrafficTreatment treatment1 = DefaultTrafficTreatment.builder() .setOutput(PORT_1) .build(); TrafficTreatment treatment2 = DefaultTrafficTreatment.builder() .setOutput(PORT_2) ...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertTime() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("time").dataType("time").build(); Column column = PostgresTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), col...
public void process(final Exchange exchange) { final ExecutionContext executionContext = smooks.createExecutionContext(); try { executionContext.put(EXCHANGE_TYPED_KEY, exchange); String charsetName = (String) exchange.getProperty(Exchange.CHARSET_NAME); if (charsetNa...
@Test public void testProcessWhenSmooksExportIsStringResult() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { from("direct:a") .process(new SmooksProcessor(new Smooks().setExports(new Exports(StringResult.class)), contex...
private static DopSettingsResource toDopSettingsResource(AlmSettingDto almSettingDto) { return new DopSettingsResource( almSettingDto.getUuid(), toResponseAlm(almSettingDto.getAlm()).name(), almSettingDto.getKey(), almSettingDto.getUrl(), almSettingDto.getAppId()); }
@Test void fetchAllDopSettings_whenDbClientReturnsData_returnsResponse() throws Exception { AlmSettingDto almSettingDto1 = generateAlmSettingsDto("github"); AlmSettingDto almSettingDto2 = generateAlmSettingsDto("azure_devops"); AlmSettingDto almSettingDto3 = generateAlmSettingsDto("bitbucket_cloud"); ...
public void validate(WorkflowCreateRequest request, User caller) { LOG.debug( "validating workflow [{}] for user [{}]", request.getWorkflow().getId(), caller.getName()); List<String> errors = new ArrayList<>(); if (request.getWorkflow() == null) { errors.add("workflow cannot be null"); } ...
@Test public void testWorkflowValidate() { WorkflowCreateRequest request = new WorkflowCreateRequest(); request.setWorkflow(definition.getWorkflow()); actionHandler.validate(request, tester); verify(dryRunValidator, times(1)).validate(any(), any()); verify(workflowDao, times(0)).addWorkflowDefinit...
public URLNormalizer removeDirectoryIndex() { String path = toURL().getPath(); if (PATTERN_PATH_LAST_SEGMENT.matcher(path).matches()) { url = StringUtils.replaceOnce( url, path, StringUtils.substringBeforeLast(path, "/") + "/"); } return this; }
@Test public void testRemoveDirectoryIndex() { s = "http://www.example.com/index.html"; t = "http://www.example.com/"; assertEquals(t, n(s).removeDirectoryIndex().toString()); s = "http://www.example.com/index.html/a"; t = "http://www.example.com/index.html/a"; assert...
@Override public Object get(PropertyKey key) { return get(key, ConfigurationValueOptions.defaults()); }
@Test public void getUnsetValueThrowsException() { mThrown.expect(RuntimeException.class); mConfiguration.get(PropertyKey.S3A_ACCESS_KEY); }
public static TencentClsLogCollectClient getTencentClsLogCollectClient() { return TENCENT_CLS_LOG_COLLECT_CLIENT; }
@Test public void testGetAliyunSlsLogCollectClient() { Assertions.assertEquals(LoggingTencentClsPluginDataHandler.getTencentClsLogCollectClient().getClass(), TencentClsLogCollectClient.class); }
@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 flags int offset = 0; final int flags = data.getIntValue(Data.FORMAT_UINT8, offse...
@Test public void onInvalidDataReceived() { success = false; final Data data = new Data(new byte[] { 0b10111, 1, 1 }); response.onDataReceived(null, data); assertFalse(response.isValid()); assertFalse(success); }
@Override public void write(int b) throws IOException { byte[] data = new byte[] { (byte) b }; write(data); }
@Test public void testWrite() throws Exception { DistributedLogManager dlm = mock(DistributedLogManager.class); AppendOnlyStreamWriter writer = mock(AppendOnlyStreamWriter.class); DLOutputStream out = new DLOutputStream(dlm, writer); byte[] data = new byte[16]; out.write(dat...
public void track(TableOperations ops) { Preconditions.checkArgument(null != ops, "Invalid table ops: null"); tracker.put(ops, ops.io()); }
@SuppressWarnings("resource") @Test public void nullTableOps() { assertThatThrownBy(() -> new FileIOTracker().track(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid table ops: null"); }
public ExitStatus(Options options) { this.options = options; }
@Test void with_passed_failed_scenarios() { createRuntime(); bus.send(testCaseFinishedWithStatus(Status.PASSED)); bus.send(testCaseFinishedWithStatus(Status.FAILED)); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1))); }
public static boolean hasText(String str) { return (str != null && !str.isEmpty() && containsText(str)); }
@Test void testHasText() { // Test case 1: Empty string assertFalse(StringUtils.hasText("")); // Test case 2: String with whitespace only assertFalse(StringUtils.hasText(" ")); // Test case 3: Null string assertFalse(StringUtils.hasText(null)); ...
static void validateEndpoint(String endpoint, String endpointName) throws MisfireException { if (StringUtils.isNotEmpty(endpoint)) { try { new URL(endpoint).toURI(); } catch (Exception e) { // Re-throw the exception to fail the input start attempt ...
@Test public void testValidateEndpoint() throws MisfireException { // Validate that no exception occurs for valid URI. KinesisTransport.validateEndpoint("https://graylog.org", "Graylog"); // Validate that no exception occurs for blank and null URL. KinesisTransport.validateEndpoint...
@Override public long extract(final ConsumerRecord<Object, Object> record, final long previousTimestamp) { try { return delegate.extract(record, previousTimestamp); } catch (final RuntimeException e) { return handleFailure(record.key(), record.value(), e); } }
@Test public void shouldLogExceptionsAndNotFailOnExtractFromRow() { // Given: final KsqlException e = new KsqlException("foo"); final LoggingTimestampExtractor extractor = new LoggingTimestampExtractor( (k, v) -> { throw e; }, logger, false ); // When: ...
public boolean checkStateUpdater(final long now, final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) { addTasksToStateUpdater(); if (stateUpdater.hasExceptionsAndFailedTasks()) { handleExceptionsFromStateUpdater(); } if ...
@Test public void shouldTransitMultipleRestoredTasksToRunning() { final StreamTask task1 = statefulTask(taskId00, taskId00ChangelogPartitions) .inState(State.RESTORING) .withInputPartitions(taskId00Partitions).build(); final StreamTask task2 = statefulTask(taskId01, taskId01C...