focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String getRomOAID() { Uri uri = Uri.parse("content://com.vivo.vms.IdProvider/IdentifierId/OAID"); String oaid = null; Cursor cursor = null; try { cursor = mContext.getContentResolver().query(uri, null, null, null, null); if...
@Test public void getRomOAID() { VivoImpl vivo = new VivoImpl(mApplication); // if (vivo.isSupported()) { // Assert.assertNull(vivo.getRomOAID()); // } }
public static String removeTrailingSlashes(String path) { return TRAILING_SLASH_PATTERN.matcher(path).replaceFirst(""); }
@Test public void removeTrailingSlashes_whenNoTrailingSlashes_returnsOriginal() { assertThat(removeTrailingSlashes("/a/b/c")).isEqualTo("/a/b/c"); }
BeanLevelInfo getFinalPath( BeanInjectionInfo.Property property ) { return ( !property.getPath().isEmpty() ) ? property.getPath().get( property.getPath().size() - 1 ) : null; }
@Test public void getFinalPath_Null() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); BeanInjectionInfo.Property noPathProperty = bii. new Property("name", "groupName", Collections.EMPTY_LIST ); assertNull(bi.getFinalPath( n...
@Override public EpoxyModel<?> remove(int index) { notifyRemoval(index, 1); return super.remove(index); }
@Test public void testRemoveIndex() { EpoxyModel<?> removedModel = modelList.remove(0); assertFalse(modelList.contains(removedModel)); assertEquals(2, modelList.size()); verify(observer).onItemRangeRemoved(0, 1); }
@Override public Scope decorateScope(@Nullable TraceContext context, Scope scope) { if (scope == Scope.NOOP) return scope; // we only scope fields constant in the context ScopeEvent event = new ScopeEvent(); if (!event.isEnabled()) return scope; if (context != null) { event.traceId = context.tra...
@Test void doesntDecorateNoop() { assertThat(decorator.decorateScope(context, Scope.NOOP)).isSameAs(Scope.NOOP); assertThat(decorator.decorateScope(null, Scope.NOOP)).isSameAs(Scope.NOOP); }
@Override public GrpcClientRequest request() { return request; }
@Test void request() { assertThat(response.request()).isSameAs(request); }
@Override public void process(final Exchange exchange) throws Exception { component.getRoutingProcessor(configuration.getChannel()) .process(exchange); }
@Test void testProcessAsynchronous() { when(configuration.getChannel()).thenReturn("testChannel"); when(component.getRoutingProcessor(anyString())).thenReturn(processor); boolean result = producer.process(exchange, asyncCallback); assertFalse(result); }
public synchronized String encrypt(String keyRingId, String keyId, String message) { CryptoKeyName keyName = CryptoKeyName.of(projectId, region, keyRingId, keyId); LOG.info("Encrypting given message using key {}.", keyName.toString()); try (KeyManagementServiceClient client = clientFactory.getKMSClient())...
@Test public void testEncryptShouldEncodeEncryptedMessageWithBase64() { String ciphertext = "ciphertext"; EncryptResponse encryptedResponse = EncryptResponse.newBuilder().setCiphertext(ByteString.copyFromUtf8(ciphertext)).build(); when(kmsClientFactory.getKMSClient()).thenReturn(serviceClient); ...
public static Labels fromString(String stringLabels) throws IllegalArgumentException { Map<String, String> labels = new HashMap<>(); try { if (stringLabels != null && !stringLabels.isEmpty()) { String[] labelsArray = stringLabels.split(","); for (String label...
@Test public void testParseInvalidLabels1() { assertThrows(IllegalArgumentException.class, () -> { String invalidLabels = ",key1=value1,key2=value2"; Labels.fromString(invalidLabels); }); }
public static FieldScope none() { return FieldScopeImpl.none(); }
@Test public void testFieldScopes_none() { Message message = parse("o_int: 3 r_string: \"foo\""); Message diffMessage = parse("o_int: 5 r_string: \"bar\""); expectThat(diffMessage).ignoringFieldScope(FieldScopes.none()).isNotEqualTo(message); expectThat(diffMessage).withPartialScope(FieldScopes.none(...
@Override @CacheEvict(value = RedisKeyConstants.ROLE, key = "#updateReqVO.id") @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_UPDATE_SUB_TYPE, bizNo = "{{#updateReqVO.id}}", success = SYSTEM_ROLE_UPDATE_SUCCESS) public void updateRole(RoleSaveReqVO updateReqVO) { // 1.1 校验是否可以...
@Test public void testUpdateRole() { // mock 数据 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType())); roleMapper.insert(roleDO); // 准备参数 Long id = roleDO.getId(); RoleSaveReqVO reqVO = randomPojo(RoleSaveReqVO.class, o -> o.setId(id)...
protected static void parse(OldExcelExtractor extractor, XHTMLContentHandler xhtml) throws TikaException, IOException, SAXException { // Get the whole text, as a single string String text = extractor.getText(); // Split and output String line; BufferedReader reader = ...
@Test public void testPlainText() throws Exception { ContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); try (TikaInputStream stream = getTestFile(file)) { new OldExcelParser().parse(stream, handler, metadata, new ParseContext()); } ...
public static boolean isDirectory(URL resourceURL) throws URISyntaxException { final String protocol = resourceURL.getProtocol(); switch (protocol) { case "jar": try { final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection(); ...
@Test void isDirectoryReturnsTrueForDirectoriesWithSpacesInJars() throws Exception { final URL url = new URL("jar:" + resourceJar.toExternalForm() + "!/dir with space/"); assertThat(url.getProtocol()).isEqualTo("jar"); assertThat(ResourceURL.isDirectory(url)).isTrue(); }
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_addNonexistentZipOfJarsWithPath_then_throwsException() { // Given String path = Paths.get("/i/do/not/exist").toString(); // Then expectedException.expect(JetException.class); expectedException.expectMessage("Not an existing, readable file: " + path); ...
public String serializeJob(Job job) { return jsonMapper.serialize(job); }
@Test void onIllegalJobParameterCorrectExceptionIsThrown() { TestService.IllegalWork illegalWork = new TestService.IllegalWork(5); Job job = anEnqueuedJob() .withJobDetails(() -> testService.doIllegalWork(illegalWork)) .build(); assertThatCode(() -> jobMapper...
@Override public String toString() { return getClass().getSimpleName() + "[period=" + getPeriod() + ", startDate=" + getStartDate() + ", endDate=" + getEndDate() + ']'; }
@Test public void testToString() { final String string = periodRange.toString(); assertNotNull("toString not null", string); assertFalse("toString not empty", string.isEmpty()); final String string2 = customRange.toString(); assertNotNull("toString not null", string2); assertFalse("toString not empty", str...
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { if (statement.getStatement() instanceof CreateSource) { return handleCreateSource((ConfiguredStatement<CreateSource>) statement); } return statem...
@Test public void shouldInjectMissingKeyAndValueFormat() { // Given givenConfig(ImmutableMap.of( KsqlConfig.KSQL_DEFAULT_KEY_FORMAT_CONFIG, "KAFKA", KsqlConfig.KSQL_DEFAULT_VALUE_FORMAT_CONFIG, "JSON" )); givenSourceProps(ImmutableMap.of()); // When final ConfiguredStatement<?...
@VisibleForTesting public int getClusterMetricsFailedRetrieved() { return numGetClusterMetricsFailedRetrieved.value(); }
@Test public void testGetClusterMetricsFailed() { long totalBadbefore = metrics.getClusterMetricsFailedRetrieved(); badSubCluster.getClusterMetrics(); Assert.assertEquals(totalBadbefore + 1, metrics.getClusterMetricsFailedRetrieved()); }
@Override public Host filter(final KsqlHostInfo host) { if (host.host().equals(activeHost.host()) && host.port() == activeHost.port()) { return Host.include(host); } return Host.exclude(host, "Host is not the active host for this partition."); }
@Test public void shouldFilterActive() { // Given: // When: final Host filterActive = activeHostFilter.filter(activeHost); final Host filterStandby = activeHostFilter.filter(standByHost); // Then: assertThat(filterActive.isSelected(), is(true)); assertThat(filterStandby.isSelected(), is(...
@Override public String getRomOAID() { String oaid = null; try { Intent intent = new Intent("com.asus.msa.action.ACCESS_DID"); ComponentName componentName = new ComponentName("com.asus.msa.SupplementaryDID", "com.asus.msa.SupplementaryDID.SupplementaryDIDService"); ...
@Test public void getRomOAID() { AsusImpl asus = new AsusImpl(mApplication); // if(asus.isSupported()) { // Assert.assertNull(asus.getRomOAID()); // } }
@Override protected Result[] run(String value) { final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly); // the extractor instance is rebuilt every second anyway final Match match = grok.match(value); final Map<String, Object> matches = matc...
@Test public void testIssue5563() { // See: https://github.com/Graylog2/graylog2-server/issues/5563 // https://github.com/Graylog2/graylog2-server/issues/5704 final Map<String, Object> config = new HashMap<>(); config.put("named_captures_only", true); patternSet.add(Gr...
@Subscribe public void inputDeleted(InputDeleted inputDeletedEvent) { LOG.debug("Input deleted: {}", inputDeletedEvent.id()); final IOState<MessageInput> inputState = inputRegistry.getInputState(inputDeletedEvent.id()); if (inputState != null) { inputRegistry.remove(inputState); ...
@Test public void inputDeletedDoesNothingIfInputIsNotRunning() throws Exception { final String inputId = "input-id"; @SuppressWarnings("unchecked") final IOState<MessageInput> inputState = mock(IOState.class); when(inputState.getState()).thenReturn(null); when(inputRegistry.g...
public void setArtifactId(String artifactId) { this.artifactId = artifactId; }
@Test public void testSetArtifactId() { String artifactId = "aaa"; String expected = "aaa"; Model instance = new Model(); instance.setArtifactId(artifactId); assertEquals(expected, instance.getArtifactId()); }
@Override public ConfigData get(String path) { return get(path, Files::isRegularFile); }
@Test public void testGetAllKeysAtPath() { ConfigData configData = provider.get(dir); assertEquals(toSet(asList(foo, bar)), configData.data().keySet()); assertEquals("FOO", configData.data().get(foo)); assertEquals("BAR", configData.data().get(bar)); assertNull(configData.ttl...
@Override public CompletableFuture<List<Long>> getSplitBoundary(BundleSplitOption bundleSplitOption) { NamespaceBundle bundle = bundleSplitOption.getBundle(); return CompletableFuture.completedFuture(Collections.singletonList(bundle.getLowerEndpoint() + (bundle.getUpperEndpoint() - b...
@Test public void testGetSplitBoundaryMethodReturnCorrectResult() { RangeEquallyDivideBundleSplitAlgorithm rangeEquallyDivideBundleSplitAlgorithm = new RangeEquallyDivideBundleSplitAlgorithm(); Assert.assertThrows(NullPointerException.class, () -> rangeEquallyDivideBundleSplitAlgorithm.getSplitBound...
public static RuleViolation isStandard(Transaction tx) { // TODO: Finish this function off. if (tx.getVersion() > 2 || tx.getVersion() < 1) { log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion()); return RuleViolation.VERSION; } ...
@Test public void nonShortestPossiblePushData() { ScriptChunk nonStandardChunk = new ScriptChunk(OP_PUSHDATA1, new byte[75]); byte[] nonStandardScript = new ScriptBuilder().addChunk(nonStandardChunk).build().program(); // Test non-standard script as an input. Transaction tx = new Tra...
@Override public RefreshNodesResourcesResponse refreshNodesResources(RefreshNodesResourcesRequest request) throws YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrRefreshNodesResourcesFailedRetrieved(); RouterServerUtil.logAndThrowException("M...
@Test public void testRefreshNodesResourcesEmptyRequest() throws Exception { // null request1. LambdaTestUtils.intercept(YarnException.class, "Missing RefreshNodesResources request.", () -> interceptor.refreshNodesResources(null)); // null request2. RefreshNodesResourcesRequest request = Refr...
@Override public OffsetFetchResponseData data() { return data; }
@Test public void testUseDefaultLeaderEpochV8() { final Optional<Integer> emptyLeaderEpoch = Optional.empty(); partitionDataMap.clear(); partitionDataMap.put(new TopicPartition(topicOne, partitionOne), new PartitionData( offset, emptyLeaderEpoch, ...
public static <T extends Comparable<T>> Pair<Integer, T> argmax(List<T> values) { if (values.isEmpty()) { throw new IllegalArgumentException("argmax on an empty list"); } // // There is no "globally min" value like -Inf for an arbitrary type T so we just pick the first list e...
@Test public void testArgmax() { assertThrows(IllegalArgumentException.class, () -> Util.argmax(new ArrayList<Double>())); List<Integer> lst = Collections.singletonList(1); Pair<Integer, Integer> argmax = Util.argmax(lst); assertEquals(0, argmax.getA()); assertEquals(1, argm...
@Override public <T> void register(Class<T> remoteInterface, T object) { register(remoteInterface, object, 1); }
@Test public void testCancelAsync() throws InterruptedException { RedissonClient r1 = createInstance(); AtomicInteger iterations = new AtomicInteger(); ExecutorService executor = Executors.newSingleThreadExecutor(); r1.getRemoteService().register(RemoteInterface.class, new RemoteImpl...
@Override public void exists(final String path, final boolean watch, final AsyncCallback.StatCallback cb, final Object ctx) { if (!SymlinkUtil.containsSymlink(path)) { _zk.exists(path, watch, cb, ctx); } else { SymlinkStatCallback compositeCallback = new SymlinkStatCallback(path, _de...
@Test public void testSymlinkWithExistWatch2() throws InterruptedException, ExecutionException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.StatCallback existCallback = new AsyncCallback.StatCallback() { @Overrid...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test(expectedExceptions = SemanticException.class, expectedExceptionsMessageRegExp = "line 1:37: Scalar subqueries in UNNEST are not supported") public void testUnnestInnerScalar() { analyze("SELECT * FROM (SELECT 1) CROSS JOIN UNNEST((SELECT array[1])) AS T(x)"); }
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldParseDropConnectorStatement() { // Given: final String dropConnector = "DRoP CONNEcTOR `jdbc-connector` ;"; // The space at the end is intentional // When: List<CommandParser.ParsedCommand> commands = parse(dropConnector); // Then: assertThat(commands.size(), is(1)); ...
void fail(Throwable throwable) { checkArgument(throwable != null, "Must be not null."); releaseInternal(throwable); // notify the netty thread which will propagate the error to the consumer task notifyDataAvailable(); }
@Test void testFail() throws Exception { int numSegments = 5; Queue<MemorySegment> segments = createsMemorySegments(numSegments); try { CountingAvailabilityListener listener = new CountingAvailabilityListener(); SortMergeSubpartitionReader subpartitionReader = ...
public static TableSchema toTableSchema(Schema schema) { return new TableSchema().setFields(toTableFieldSchema(schema)); }
@Test public void testToTableSchema_row() { TableSchema schema = toTableSchema(ROW_TYPE); assertThat(schema.getFields().size(), equalTo(1)); TableFieldSchema field = schema.getFields().get(0); assertThat(field.getName(), equalTo("row")); assertThat(field.getType(), equalTo(StandardSQLTypeName.STR...
public static boolean isValidAndroidId(String androidId) { if (TextUtils.isEmpty(androidId)) { return false; } return !mInvalidAndroidId.contains(androidId.toLowerCase(Locale.getDefault())); }
@Test public void isValidAndroidId() { }
@Override public boolean register(final Application application) { try { if(finder.isInstalled(application)) { service.add(new FinderLocal(workspace.absolutePathForAppBundleWithIdentifier(application.getIdentifier()))); return true; } retur...
@Test public void testRegisterNotInstalled() { final SharedFileListApplicationLoginRegistry registry = new SharedFileListApplicationLoginRegistry(new DisabledApplicationFinder()); assertFalse(registry.register(new Application("ch.sudo.cyberduck"))); }
public RewriteGroupedCode rewrite(String context) { BlockStatementGrouperVisitor visitor = new BlockStatementGrouperVisitor(maxMethodLength, parameters); visitor.visitStatement(topStatement, context); final Map<String, List<String>> groupStrings = visitor.rewrite(rewriter); ...
@Test public void testExtractWhileInIfGroups() { String parameters = "a, b"; String givenBlock = readResource("groups/code/WhileInIf.txt"); String expectedBlock = readResource("groups/expected/WhileInIf.txt"); BlockStatementGrouper grouper = new BlockStatementGrouper(givenBlock, 10,...
public static boolean isBlank(CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } ...
@Test void testIsBlank() throws Exception { assertTrue(StringUtils.isBlank(null)); assertTrue(StringUtils.isBlank("")); assertFalse(StringUtils.isBlank("abc")); }
public static String truncateUtf8(String str, int maxBytes) { Charset charset = StandardCharsets.UTF_8; //UTF-8编码单个字符最大长度4 return truncateByByteLength(str, charset, maxBytes, 4, true); }
@Test public void truncateUtf8Test2() { final String str = "这是This一"; final String ret = StrUtil.truncateUtf8(str, 13); assertEquals("这是This一", ret); }
@Override public Optional<ConfigTable> readConfig(Set<String> keys) { removeUninterestedKeys(keys); registerKeyListeners(keys); final ConfigTable table = new ConfigTable(); configItemKeyedByName.forEach((key, value) -> { if (value.isPresent()) { table.a...
@Test public void shouldUnsubscribeWhenKeyRemoved() { cacheByKey = new ConcurrentHashMap<>(); KVCache existedCache = mock(KVCache.class); cacheByKey.put("existedKey", existedCache); configItemKeyedByName = new ConcurrentHashMap<>(); Whitebox.setInternalState(register, "cache...
@Override public void removeSensor(final Sensor sensor) { Objects.requireNonNull(sensor, "Sensor is null"); metrics.removeSensor(sensor.name()); final Sensor parent = parentSensors.remove(sensor); if (parent != null) { metrics.removeSensor(parent.name()); } }
@Test public void testRemoveSensor() { final String sensorName = "sensor1"; final String scope = "scope"; final String entity = "entity"; final String operation = "put"; final Sensor sensor1 = streamsMetrics.addSensor(sensorName, RecordingLevel.DEBUG); streamsMetrics...
@VisibleForTesting static String truncateLongClasspath(ImmutableList<String> imageEntrypoint) { List<String> truncated = new ArrayList<>(); UnmodifiableIterator<String> iterator = imageEntrypoint.iterator(); while (iterator.hasNext()) { String element = iterator.next(); truncated.add(element);...
@Test public void testTruncateLongClasspath_longClasspath() { String classpath = "/app/resources:/app/classes:/app/libs/spring-boot-starter-web-2.0.3.RELEASE.jar:/app/libs/" + "shared-library-0.1.0.jar:/app/libs/spring-boot-starter-json-2.0.3.RELEASE.jar:/app/" + "libs/spring-boot-...
private CompletableFuture<Void> seekAsyncInternal(long requestId, ByteBuf seek, MessageId seekId, Long seekTimestamp, String seekBy) { AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new B...
@Test public void testSeekAsyncInternal() { // given ClientCnx cnx = mock(ClientCnx.class); CompletableFuture<ProducerResponse> clientReq = new CompletableFuture<>(); when(cnx.sendRequestWithId(any(ByteBuf.class), anyLong())).thenReturn(clientReq); ScheduledExecutorProvider ...
@Override public Object getValue() { try { return mBeanServerConn.getAttribute(getObjectName(), attributeName); } catch (IOException | JMException e) { return null; } }
@Test public void returnsNullIfMBeanNotFound() throws Exception { ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); assertThat(gauge.getValue()).isNull(); }
@Override public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException { getExecuteClientProxy(instance).deregisterService(serviceName, groupName, instance); }
@Test void testDeregisterEphemeralServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); instance.setServiceName(serviceName); instance.setClusterName(groupName); instance.setIp("1.1.1.1"...
@Override public Map<String, Map<String, String>> getAdditionalInformation() { Map<String, Map<String, String>> result = Maps.newHashMap(); result.put("values", values); return result; }
@Test public void testGetValues() throws Exception { Map<String,String> values = Maps.newHashMap(); values.put("foo", "bar"); values.put("zomg", "baz"); DropdownField f = new DropdownField("test", "Name", "fooval", values, ConfigurationField.Optional.NOT_OPTIONAL); assertEqu...
@VisibleForTesting static boolean isRichConsole(ConsoleOutput consoleOutput, HttpTraceLevel httpTraceLevel) { if (httpTraceLevel != HttpTraceLevel.off) { return false; } switch (consoleOutput) { case plain: return false; case auto: // Enables progress footer when ANSI is...
@Test public void testIsRichConsole_true() { assertThat(CliLogger.isRichConsole(ConsoleOutput.rich, HttpTraceLevel.off)).isTrue(); }
String deleteAll(int n) { return deleteAllQueries.computeIfAbsent(n, deleteAllFactory); }
@Test public void testDeleteAllIsQuoted() { Queries queries = new Queries(mapping, idColumn, columnMetadata); String result = queries.deleteAll(2); assertEquals("DELETE FROM \"mymapping\" WHERE \"id\" IN (?, ?)", result); }
@VisibleForTesting public void validateDictDataValueUnique(Long id, String dictType, String value) { DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value); if (dictData == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典数据 if (id == null) ...
@Test public void testValidateDictDataValueUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String dictType = randomString(); String value = randomString(); // mock 数据 dictDataMapper.insert(randomDictDataDO(o -> { o.setDictType(dictType...
public void logOnCommitPosition( final int memberId, final long leadershipTermId, final long logPosition, final int leaderId) { final int length = 2 * SIZE_OF_LONG + 2 * SIZE_OF_INT; final int encodedLength = encodedLength(length); final ManyToOneRingBuffer ri...
@Test void logOnCommitPosition() { final int offset = ALIGNMENT * 4; logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset); final long leadershipTermId = 1233L; final long logPosition = 988723465L; final int leaderId = 982374; final int memberId = 2; ...
public Mono<CosmosDatabaseResponse> createDatabase( final String databaseName, final ThroughputProperties throughputProperties) { CosmosDbUtils.validateIfParameterIsNotEmpty(databaseName, PARAM_DATABASE_NAME); return client.createDatabaseIfNotExists(databaseName, throughputProperties); ...
@Test void testCreateDatabase() { final CosmosAsyncClientWrapper client = mock(CosmosAsyncClientWrapper.class); when(client.createDatabaseIfNotExists(any(), any())).thenReturn(Mono.just(mock(CosmosDatabaseResponse.class))); final CosmosDbClientOperations operations = CosmosDbClientOperation...
public TopicRouteData pickupTopicRouteData(final String topic) { TopicRouteData topicRouteData = new TopicRouteData(); boolean foundQueueData = false; boolean foundBrokerData = false; List<BrokerData> brokerDataList = new LinkedList<>(); topicRouteData.setBrokerDatas(brokerDataLi...
@Test public void testPickupTopicRouteData() { TopicRouteData result = routeInfoManager.pickupTopicRouteData("unit_test"); assertThat(result).isNull(); }
@Override public Span start() { return start(clock.currentTimeMicroseconds()); }
@Test void start() { span.start(); span.flush(); assertThat(spans.get(0).startTimestamp()) .isPositive(); }
public void add() { add(1L, defaultPosition); }
@Test final void testAddLong() { final String metricName = "unitTestCounter"; Counter c = receiver.declareCounter(metricName); final long twoToThePowerOfFourtyeight = 65536L * 65536L * 65536L; c.add(twoToThePowerOfFourtyeight); Bucket b = receiver.getSnapshot(); final...
@HighFrequencyInvocation public EncryptColumn getEncryptColumn(final String logicColumnName) { ShardingSpherePreconditions.checkState(isEncryptColumn(logicColumnName), () -> new EncryptColumnNotFoundException(table, logicColumnName)); return columns.get(logicColumnName); }
@Test void assertGetEncryptColumn() { assertNotNull(encryptTable.getEncryptColumn("logicColumn")); }
@Override public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) { return internal.query(query, positionBound, config); }
@Test public void shouldTrackOpenIteratorsMetric() { final MultiVersionedKeyQuery<String, String> query = MultiVersionedKeyQuery.withKey(KEY); final PositionBound bound = PositionBound.unbounded(); final QueryConfig config = new QueryConfig(false); when(inner.query(any(), any(), any(...
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testProcessElementExceptionWithReturn() throws Exception { thrown.expect(UserCodeException.class); thrown.expectMessage("bogus"); DoFnInvokers.invokerFor( new DoFn<Integer, Integer>() { @ProcessElement public ProcessContinuation processElement( ...
public void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk) throws IOException { selectInputStreams(streams, fromTxnId, inProgressOk, false); }
@Test public void testSelectInputStreamsMajorityDown() throws Exception { // Shut down all of the JNs. cluster.shutdown(); List<EditLogInputStream> streams = Lists.newArrayList(); try { qjm.selectInputStreams(streams, 0, false); fail("Did not throw IOE"); } catch (QuorumException ioe)...
public static Charset getCharset(HttpMessage message) { return getCharset(message, CharsetUtil.ISO_8859_1); }
@Test public void testGetCharset() { testGetCharsetUtf8("text/html; charset=utf-8"); }
@Override protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException { final NSDictionary serialized = NSDictionary.dictionaryWithContentsOfFile(file.getAbsolute()); if(null == serialized) { throw new LocalAccessDeniedException(String.format("Inv...
@Test public void testParse() throws Exception { CloudMounterBookmarkCollection c = new CloudMounterBookmarkCollection(); assertEquals(0, c.size()); c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList( new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), ...
public static ClusterHealthStatus isHealth(List<RemoteInstance> remoteInstances) { if (CollectionUtils.isEmpty(remoteInstances)) { return ClusterHealthStatus.unHealth("can't get the instance list"); } if (!CoreModuleConfig.Role.Receiver.equals(ROLE)) { List<RemoteInstance...
@Test public void unHealthWithNullInstance() { ClusterHealthStatus clusterHealthStatus = OAPNodeChecker.isHealth(null); Assertions.assertFalse(clusterHealthStatus.isHealth()); }
public static void main(String[] args) { final var inventory = new Inventory(1000); var executorService = Executors.newFixedThreadPool(3); IntStream.range(0, 3).<Runnable>mapToObj(i -> () -> { while (inventory.addItem(new Item())) { LOGGER.info("Adding another item"); } }).forEach(ex...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public boolean touch(URI uri) throws IOException { try { HeadObjectResponse s3ObjectMetadata = getS3ObjectMetadata(uri); String encodedUrl = URLEncoder.encode(uri.getHost() + uri.getPath(), StandardCharsets.UTF_8); String path = sanitizePath(uri.getPath()); CopyObjectReque...
@Test public void testTouchFilesInFolder() throws Exception { String folder = "my-files"; String[] originalFiles = new String[]{"a-touch.txt", "b-touch.txt", "c-touch.txt"}; for (String fileName : originalFiles) { String fileNameWithFolder = folder + DELIMITER + fileName; _s3PinotFS.to...
public static <T> Window<T> into(WindowFn<? super T, ?> fn) { try { fn.windowCoder().verifyDeterministic(); } catch (NonDeterministicException e) { throw new IllegalArgumentException("Window coders must be deterministic.", e); } return Window.<T>configure().withWindowFn(fn); }
@Test @Category({ValidatesRunner.class, UsesCustomWindowMerging.class}) public void testMergingCustomWindowsKeyedCollection() { Instant startInstant = new Instant(0L); PCollection<KV<Integer, String>> inputCollection = pipeline.apply( Create.timestamped( TimestampedValue....
@Override public Optional<ShardingConditionValue> generate(final BetweenExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { ConditionValue betweenConditionValue = new ConditionValue(predicate.getBetweenExpr(), params); ConditionVal...
@SuppressWarnings("unchecked") @Test void assertGenerateOneNowConditionValue() { Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); ExpressionSegment betweenSegment = new LiteralExpressionSegment(0, 0, timestamp); ExpressionSegment andSegment = new CommonExpressionSegment(0, 0...
public static File getPluginFile(final String path) { String pluginPath = getPluginPath(path); return new File(pluginPath); }
@Test public void testGetPluginPathByPluginExt() { System.setProperty("plugin-ext", "/testUrl"); File jarFile = ShenyuPluginPathBuilder.getPluginFile(""); assertNotNull(jarFile); }
@Override public Boolean run(final Session<?> session) throws BackgroundException { final UnixPermission feature = session.getFeature(UnixPermission.class); if(log.isDebugEnabled()) { log.debug(String.format("Run with feature %s", feature)); } for(Path file : files) { ...
@Test public void testRun() throws Exception { final PermissionOverwrite permission = new PermissionOverwrite( new PermissionOverwrite.Action(true, true, true), new PermissionOverwrite.Action(null, false, false), new PermissionOverwrite.Action(true, false, fal...
public ProtocolBuilder register(Boolean register) { this.register = register; return getThis(); }
@Test void register() { ProtocolBuilder builder = new ProtocolBuilder(); builder.register(true); Assertions.assertTrue(builder.build().isRegister()); }
public String getUUID() { if (CatalogMgr.isExternalCatalog(catalogName)) { return catalogName + "." + fullQualifiedName; } return Long.toString(id); }
@Test public void testGetUUID() { // Internal database Database db1 = new Database(); Assert.assertEquals("0", db1.getUUID()); Database db2 = new Database(101, "db2"); Assert.assertEquals("101", db2.getUUID()); // External database Database db3 = new Databas...
public static List<String> resolveCompsDependency(Service service) { List<String> components = new ArrayList<String>(); for (Component component : service.getComponents()) { int depSize = component.getDependencies().size(); if (!components.contains(component.getName())) { components.add(comp...
@Test public void testResolveNoCompsDependency() { Service service = createExampleApplication(); Component compa = createComponent("compa"); Component compb = createComponent("compb"); service.addComponent(compa); service.addComponent(compb); List<String> order = ServiceApiUtil.resolveCompsDep...
public static String getPrefix(URI uri, ClassLoader classLoader) { if (uri == null && classLoader == null) { return null; } else { StringBuilder sb = new StringBuilder(); if (uri != null) { sb.append(uri.toASCIIString()).append('/'); } ...
@Test public void testGetPrefix() { String prefix = getPrefix(uri, classLoader); assertEquals(expectedPrefix, prefix); }
public void log(QueryLogParams params) { _logger.debug("Broker Response: {}", params._response); if (!(_logRateLimiter.tryAcquire() || shouldForceLog(params))) { _numDroppedLogs.incrementAndGet(); return; } final StringBuilder queryLogBuilder = new StringBuilder(); for (QueryLogEntry v...
@Test public void shouldForceLogWhenExceptionsExist() { // Given: Mockito.when(_logRateLimiter.tryAcquire()).thenReturn(false); QueryLogger.QueryLogParams params = generateParams(false, 1, 456); QueryLogger queryLogger = new QueryLogger(_logRateLimiter, 100, true, _logger, _droppedRateLimiter); /...
@Override public COSDictionary getCOSObject() { return dictionary; }
@Test void createWidgetAnnotationFromField() { PDDocument document = new PDDocument(); PDAcroForm acroForm = new PDAcroForm(document); PDTextField textField = new PDTextField(acroForm); PDAnnotation annotation = textField.getWidgets().get(0); assertEquals(COSName.ANNOT, a...
@Bean public ShenyuPlugin signPlugin(final SignService signService, final ServerCodecConfigurer configurer) { return new SignPlugin(configurer.getReaders(), signService); }
@Test public void testSignPlugin() { applicationContextRunner.run(context -> { ShenyuPlugin plugin = context.getBean("signPlugin", ShenyuPlugin.class); assertNotNull(plugin); assertThat(plugin.named()).isEqualTo(PluginEnum.SIGN.getName()); } ...
@Udf(description = "Splits a string into an array of substrings based on a delimiter.") public List<String> split( @UdfParameter( description = "The string to be split. If NULL, then function returns NULL.") final String string, @UdfParameter( description = "The delimiter to spli...
@Test public void shouldReturnNullOnAnyNullParametersOnSplitBytes() { assertThat(splitUdf.split(null, EMPTY_BYTES), is(nullValue())); assertThat(splitUdf.split(EMPTY_BYTES, null), is(nullValue())); assertThat(splitUdf.split((ByteBuffer) null, null), is(nullValue())); }
@Override public StageBundleFactory forStage(ExecutableStage executableStage) { return new SimpleStageBundleFactory(executableStage); }
@Test public void createsCorrectEnvironment() throws Exception { try (DefaultJobBundleFactory bundleFactory = createDefaultJobBundleFactory(envFactoryProviderMap)) { bundleFactory.forStage(getExecutableStage(environment)); verify(envFactory).createEnvironment(eq(environment), any()); } }
@Override public int hashCode() { return Objects.hash(numBits, numHashFunctions, Arrays.hashCode(bitSet.getData())); }
@Test public void testHashCode() { List<Long> bitset1 = ImmutableList.of(2L); List<Long> bitset2 = ImmutableList.of(2L); HiveBloomFilter filter1 = new HiveBloomFilter(bitset1, 1, 1); HiveBloomFilter filter2 = new HiveBloomFilter(bitset2, 1, 1); assertEquals(filter1, filte...
@Override public Path copy(final Path source, final Path copy, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { final CloudBlob target = session.getClient().getContainerReference(containerService.getContainer(copy)....
@Test public void testCopy() throws Exception { final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new AzureTouchFeature(session, null).touch( new Path(container, new AlphanumericRandomStringService().random(), EnumSet.o...
private ContentType getContentType(Exchange exchange) throws ParseException { String contentTypeStr = ExchangeHelper.getContentType(exchange); if (contentTypeStr == null) { contentTypeStr = DEFAULT_CONTENT_TYPE; } ContentType contentType = new ContentType(contentTypeStr); ...
@Test public void roundtripWithBinaryAttachmentsAndBinaryContent() throws IOException { String attContentType = "application/binary"; byte[] attText = { 0, 1, 2, 3, 4, 5, 6, 7 }; String attFileName = "Attachment File Name"; in.setBody("Body text"); DataSource ds = new ByteArr...
public static BigDecimal ensureFit(final BigDecimal value, final Schema schema) { return ensureFit(value, precision(schema), scale(schema)); }
@Test public void shouldEnsureFitIfExactMatch() { // No Exception When: DecimalUtil.ensureFit(new BigDecimal("1.2"), DECIMAL_SCHEMA); }
public AtomicLong getNextIndex(String virtualHostname, boolean secure) { Map<String, VipIndexSupport> index = (secure) ? secureVirtualHostNameAppMap : virtualHostNameAppMap; return Optional.ofNullable(index.get(virtualHostname.toUpperCase(Locale.ROOT))) .map(VipIndexSupport::getRoundRobi...
@Test public void testGetNextIndex() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName...
public TaskIOMetricGroup(TaskMetricGroup parent) { this(parent, SystemClock.getInstance()); }
@Test void testTaskIOMetricGroup() throws InterruptedException { TaskMetricGroup task = UnregisteredMetricGroups.createUnregisteredTaskMetricGroup(); ManualClock clock = new ManualClock(System.currentTimeMillis()); TaskIOMetricGroup taskIO = new TaskIOMetricGroup(task, clock); // te...
static int parseMajorJavaVersion(String javaVersion) { int version = parseDotted(javaVersion); if (version == -1) { version = extractBeginningInt(javaVersion); } if (version == -1) { return 6; // Choose minimum supported JDK version as default } return version; }
@Test public void testJava7() { // http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html assertThat(JavaVersion.parseMajorJavaVersion("1.7.0")).isEqualTo(7); }
public Serde<GenericKey> buildKeySerde( final FormatInfo format, final PhysicalSchema schema, final QueryContext queryContext ) { final String loggerNamePrefix = QueryLoggerUtil.queryLoggerName(queryId, queryContext); schemas.trackKeySerdeCreation( loggerNamePrefix, schema.logicalSchema...
@Test public void shouldBuildWindowedKeySerde() { // Then: runtimeBuildContext.buildKeySerde( FORMAT_INFO, WINDOW_INFO, PHYSICAL_SCHEMA, queryContext ); // Then: verify(keySerdeFactory).create( FORMAT_INFO, WINDOW_INFO, PHYSICAL_SCHEMA.keySc...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMapViaMultimapEntriesAndKeysMergeLocalAddRemoveClear() { final String tag = "map"; StateTag<MapState<byte[], Integer>> addr = StateTags.map(tag, ByteArrayCoder.of(), VarIntCoder.of()); MapState<byte[], Integer> mapState = underTestMapViaMultimap.state(NAMESPACE, addr); f...
@Deprecated public CompletableFuture<Void> disableOwnership(NamespaceBundle bundle) { return updateBundleState(bundle, false) .thenCompose(__ -> { ResourceLock<NamespaceEphemeralData> lock = locallyAcquiredLocks.get(bundle); if (lock == null) { ...
@Test public void testDisableOwnership() throws Exception { OwnershipCache cache = new OwnershipCache(this.pulsar, nsService); NamespaceBundle testBundle = new NamespaceBundle(NamespaceName.get("pulsar/test/ns-1"), Range.closedOpen(0L, (long) Integer.MAX_VALUE), bund...
public CompletableFuture<Result> getTerminationFuture() { return terminationFuture; }
@Test void testUnexpectedTaskManagerTerminationFailsRunnerFatally() throws Exception { final CompletableFuture<Void> terminationFuture = new CompletableFuture<>(); final TestingTaskExecutorService taskExecutorService = TestingTaskExecutorService.newBuilder() ....
@Override public Object evaluateLiteralExpression(String rawExpression, String className, List<String> genericClasses) { Object expressionResult = compileAndExecute(rawExpression, new HashMap<>()); Class<Object> requiredClass = loadClass(className, classLoader); if (expressionResult != null ...
@Ignore("https://issues.redhat.com/browse/DROOLS-4649") @Test public void evaluateLiteralExpression_Array() { assertThat(evaluateLiteralExpression("{\"Jim\", \"Michael\"}", Object[].class)).isEqualTo(new String[]{"Jim", "Michael"}); assertThat(evaluateLiteralExpression("{ }", Object[].class)).i...
protected void mergeAndRevive(ConsumeReviveObj consumeReviveObj) throws Throwable { ArrayList<PopCheckPoint> sortList = consumeReviveObj.genSortList(); POP_LOGGER.info("reviveQueueId={}, ck listSize={}", queueId, sortList.size()); if (sortList.size() != 0) { POP_LOGGER.info("reviveQu...
@Test public void testReviveMsgFromCk_messageNotFound_needRetry_noEnd() throws Throwable { brokerConfig.setSkipWhenCKRePutReachMaxTimes(false); PopCheckPoint ck = buildPopCheckPoint(0, 0, 0); ck.setRePutTimes(Byte.MAX_VALUE + ""); PopReviveService.ConsumeReviveObj reviveObj = new Pop...
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) { Predicate<String> packageFilter = buildPackageFilter(request); resolve(request, engineDescriptor, packageFilter); filter(engineDescriptor, packageFilter); pruneTree(engineDescriptor); }
@Test void resolveRequestWithClassSelectorShouldLogWarnIfNoFeaturesFound(LogRecordListener logRecordListener) { DiscoverySelector resource = selectClass(NoFeatures.class); EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource); resolver.resolveSelectors(discoveryRequest, tes...
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenValidStringCell_parses() { DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("lithium", "lithium"); Schema schema = Schema.builder().addStringField("a_string").addDateTimeField("a_datetime").build(); assertEquals( cellToExpectedValue.getValue(), CsvIO...
public SelectorService getSelectorService() { return selectorService; }
@Test public void testGetSelectorService() { assertEquals(selectorService, abstractShenyuClientRegisterService.getSelectorService()); }
@Udf public List<String> keys(@UdfParameter final String jsonObj) { if (jsonObj == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonObj); if (node.isMissingNode() || !node.isObject()) { return null; } final List<String> ret = new ArrayList<>(); node.fi...
@Test(expected = KsqlFunctionException.class) public void shouldReturnNullForInvalidJson() { udf.keys("abc"); }
public void register(OpChain operatorChain) { Future<?> scheduledFuture = _executorService.submit(new TraceRunnable() { @Override public void runJob() { boolean isFinished = false; TransferableBlock returnedErrorBlock = null; Throwable thrown = null; try { LOGGE...
@Test public void shouldScheduleSingleOpChainRegisteredAfterStart() throws InterruptedException { OpChain opChain = getChain(_operatorA); OpChainSchedulerService schedulerService = new OpChainSchedulerService(_executor); CountDownLatch latch = new CountDownLatch(1); Mockito.when(_operatorA.next...
@Override public Map<String, String> generationCodes(Long tableId) { // 校验是否已经存在 CodegenTableDO table = codegenTableMapper.selectById(tableId); if (table == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } List<CodegenColumnDO> columns = codegenColumnMapper.se...
@Test public void testGenerationCodes_sub_tableNotExists() { // mock 数据(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene()) .setTemplateType(CodegenTemplateTypeEnum.MASTER_NORMAL.getType())...
@Deprecated public Collection<MessageQueue> queuesWithNamespace(Collection<MessageQueue> queues) { if (StringUtils.isEmpty(this.getNamespace())) { return queues; } Iterator<MessageQueue> iter = queues.iterator(); while (iter.hasNext()) { MessageQueue queue = i...
@Test public void testQueuesWithNamespace() { MessageQueue messageQueue = new MessageQueue(); messageQueue.setTopic("defaultTopic"); Collection<MessageQueue> messageQueues = clientConfig.queuesWithNamespace(Collections.singleton(messageQueue)); assertTrue(messageQueues.contains(messa...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testShouldRaiseOutOfOrderSequenceExceptionToUserIfLogWasNotTruncated() throws Exception { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProduce...
@VisibleForTesting void updateBackoffMetrics(int retryCount, int statusCode) { if (abfsBackoffMetrics != null) { if (statusCode < HttpURLConnection.HTTP_OK || statusCode >= HttpURLConnection.HTTP_INTERNAL_ERROR) { synchronized (this) { if (retryCount >= maxIoRetries) { ...
@Test public void testBackoffRetryMetrics() throws Exception { // Create an AzureBlobFileSystem instance. final Configuration configuration = getRawConfiguration(); configuration.set(FS_AZURE_METRIC_FORMAT, String.valueOf(MetricFormat.INTERNAL_BACKOFF_METRIC_FORMAT)); final AzureBlobFileSystem fs = (A...
public Response listDumpFiles(String topologyId, String hostPort, String user) throws IOException { String portStr = hostPort.split(":")[1]; Path rawDir = logRoot.resolve(topologyId).resolve(portStr); Path absDir = rawDir.toAbsolutePath().normalize(); if (!absDir.startsWith(logRoot) || !...
@Test public void testListDumpFilesTraversalInTopoId() throws Exception { try (TmpPath rootPath = new TmpPath()) { LogviewerProfileHandler handler = createHandlerTraversalTests(rootPath.getFile().toPath()); Response response = handler.listDumpFiles("../../", "localhost:logs", "user...