focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
@Transactional
public boolean updateAfterApproval(Long userId, Integer userType, String clientId, Map<String, Boolean> requestedScopes) {
// 如果 requestedScopes 为空,说明没有要求,则返回 true 通过
if (CollUtil.isEmpty(requestedScopes)) {
return true;
}
// 更新批准的信息
... | @Test
public void testUpdateAfterApproval_none() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
// 调用
boolean success = oauth2ApproveService.updateAfterApproval(userId, userTyp... |
@Override
public Collection<RedisServer> masters() {
List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS);
return toRedisServersList(masters);
} | @Test
public void testMasters() {
Collection<RedisServer> masters = connection.masters();
assertThat(masters).hasSize(1);
} |
@Override
public Num calculate(BarSeries series, Position position) {
return position.getProfit();
} | @Test
public void calculateOnlyWithProfitPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series, series.numOf(50)),
Trade.sellAt(2, series, series.numOf(50)), Trade.bu... |
@Override
public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() {
Iterable<RedisClusterNode> res = clusterGetNodes();
Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>();
for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.... | @Test
public void testClusterGetMasterSlaveMap() {
Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap();
assertThat(map).hasSize(3);
for (Collection<RedisClusterNode> slaves : map.values()) {
assertThat(slaves).hasSize(1);
}
... |
@Override
public void reset() {
super.reset();
this.minDeltaInCurrentBlock = Integer.MAX_VALUE;
} | @Test
public void randomDataTest() throws IOException {
int maxSize = 1000;
int[] data = new int[maxSize];
for (int round = 0; round < 100000; round++) {
int size = random.nextInt(maxSize);
for (int i = 0; i < size; i++) {
data[i] = random.nextInt();
}
shouldReadAndWrite... |
public Gson create() {
List<TypeAdapterFactory> factories =
new ArrayList<>(this.factories.size() + this.hierarchyFactories.size() + 3);
factories.addAll(this.factories);
Collections.reverse(factories);
List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>(this.hierarchyFactories);
... | @Test
public void testDefaultStrictness() throws IOException {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
assertThat(gson.newJsonReader(new StringReader("{}")).getStrictness())
.isEqualTo(Strictness.LEGACY_STRICT);
assertThat(gson.newJsonWriter(new StringWriter()).g... |
public synchronized LogAction record(double... values) {
return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values);
} | @Test
public void testLoggingWithValue() {
assertTrue(helper.record(1).shouldLog());
for (int i = 0; i < 4; i++) {
timer.advance(LOG_PERIOD / 5);
assertFalse(helper.record(i % 2 == 0 ? 0 : 1).shouldLog());
}
timer.advance(LOG_PERIOD);
LogAction action = helper.record(0.5);
assert... |
@Override
public Result reconcile(Request request) {
client.fetch(Theme.class, request.name())
.ifPresent(theme -> {
if (isDeleted(theme)) {
cleanUpResourcesAndRemoveFinalizer(request.name());
return;
}
addFi... | @Test
void reconcileDeleteRetry() {
Theme theme = fakeTheme();
final MetadataOperator metadata = theme.getMetadata();
Path testWorkDir = tempDirectory.resolve("reconcile-delete");
when(themeRoot.get()).thenReturn(testWorkDir);
final ThemeReconciler themeReconciler =
... |
public Optional<Long> getTokenTimeout(
final Optional<String> token,
final KsqlConfig ksqlConfig,
final Optional<KsqlAuthTokenProvider> authTokenProvider
) {
final long maxTimeout =
ksqlConfig.getLong(KsqlConfig.KSQL_WEBSOCKET_CONNECTION_MAX_TIMEOUT_MS);
if (maxTimeout > 0) {
i... | @Test
public void shouldReturnDefaultWhenNoTokenPresent() {
assertThat(authenticationUtil.getTokenTimeout(Optional.empty(), ksqlConfig, Optional.of(authTokenProvider)), equalTo(Optional.of(60000L)));
} |
private void stop(int numOfServicesStarted, boolean stopOnlyStartedServices) {
// stop in reverse order of start
Exception firstException = null;
List<Service> services = getServices();
for (int i = numOfServicesStarted - 1; i >= 0; i--) {
Service service = services.get(i);
if (LOG.isDebugEn... | @Test(timeout = 10000)
public void testAddStartedChildInStop() throws Throwable {
CompositeService parent = new CompositeService("parent");
BreakableService child = new BreakableService();
child.init(new Configuration());
child.start();
parent.init(new Configuration());
parent.start();
par... |
public Exchange createDbzExchange(DebeziumConsumer consumer, final SourceRecord sourceRecord) {
final Exchange exchange;
if (consumer != null) {
exchange = consumer.createExchange(false);
} else {
exchange = super.createExchange();
}
final Message message... | @Test
void testIfCreatesExchangeFromSourceUpdateRecord() {
final SourceRecord sourceRecord = createUpdateRecord();
final Exchange exchange = debeziumEndpoint.createDbzExchange(null, sourceRecord);
final Message inMessage = exchange.getIn();
assertNotNull(exchange);
// asser... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testConvertersAreExecutedInOrder() throws Exception {
final Converter converter1 = new TestConverter.Builder()
.callback(new Function<Object, Object>() {
@Nullable
@Override
public Object apply(Object input) {
... |
public FEELFnResult<String> invoke(@ParameterName("from") Object val) {
if ( val == null ) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) );
}
} | @Test
void invokeDurationDays() {
FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofDays(9)), "P9D");
FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofDays(-9)), "-P9D");
} |
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception {
LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation);
MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con... | @Test
public void shouldNotAllowMultiplePackagesWithSameId() throws Exception {
Configuration packageConfiguration = new Configuration(getConfigurationProperty("name", false, "go-agent"));
Configuration repositoryConfiguration = new Configuration(getConfigurationProperty("url", false, "http://go"));... |
public boolean accept(final T t) {
checkContext();
if (isComplete() || hasSentComplete()) {
throw new IllegalStateException("Cannot call accept after complete is called");
}
if (!isCancelled() && !isFailed()) {
if (getDemand() == 0) {
buffer.add(t);
} else {
doOnNext(t)... | @Test
public void shouldNotAllowAcceptingAfterComplete() throws Exception {
TestSubscriber<String> subscriber = new TestSubscriber<>(context);
subscribeOnContext(subscriber);
execOnContextAndWait(getBufferedPublisher()::complete);
AtomicBoolean failed = new AtomicBoolean();
execOnContextAndWait(()... |
@Udf
public String chr(@UdfParameter(
description = "Decimal codepoint") final Integer decimalCode) {
if (decimalCode == null) {
return null;
}
if (!Character.isValidCodePoint(decimalCode)) {
return null;
}
final char[] resultChars = Character.toChars(decimalCode);
return Str... | @Test
public void shouldConvertControlChar() {
final String result = udf.chr(9);
assertThat(result, is("\t"));
} |
@Override
public double getStdDev() {
// two-pass algorithm for variance, avoids numeric overflow
if (values.length <= 1) {
return 0;
}
final double mean = getMean();
double variance = 0;
for (int i = 0; i < values.length; i++) {
final doubl... | @Test
public void calculatesTheStdDev() throws Exception {
assertThat(snapshot.getStdDev())
.isEqualTo(1.2688, offset(0.0001));
} |
@Override
public Object decorate(RequestedField field, Object value, SearchUser searchUser) {
try {
final Node node = nodeService.byNodeId(value.toString());
return node.getTitle();
} catch (NodeNotFoundException e) {
return value;
}
} | @Test
void testUnknownNode() {
final Object decorated = decorator.decorate(RequestedField.parse(Message.FIELD_GL2_SOURCE_NODE),
"2e7e1436-9ca4-43e3-b857-c75e61dea424",
TestSearchUser.builder().build());
Assertions.assertThat(decorated).isEqualTo("2e7e1436-9ca4-43e3-b... |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
GitMaterial that = (GitMaterial) o;
return Objects.equals(url, that.url) &&
Objects.equals(re... | @Test
void shouldNotBeEqualWhenTypeDifferent() {
Material material = MaterialsMother.gitMaterials("url1").get(0);
final Material hgMaterial = MaterialsMother.hgMaterials("url1", "hgdir").get(0);
assertThat(material.equals(hgMaterial)).isFalse();
assertThat(hgMaterial.equals(material)... |
@Override
public void seek(long newPos) {
Preconditions.checkState(!closed, "already closed");
Preconditions.checkArgument(newPos >= 0, "position is negative: %s", newPos);
// this allows a seek beyond the end of the stream but the next read will fail
next = newPos;
} | @Test
public void testSeek() throws Exception {
S3URI uri = new S3URI("s3://bucket/path/to/seek.dat");
byte[] expected = randomData(1024 * 1024);
writeS3Data(uri, expected);
try (SeekableInputStream in = new S3InputStream(s3, uri)) {
in.seek(expected.length / 2);
byte[] actual = new byte... |
@JsonProperty
public URI getUri()
{
return uri;
} | @Test
public void testQueryDividedIntoSplitsFirstSplitHasRightTime()
throws URISyntaxException
{
Instant now = LocalDateTime.of(2019, 10, 2, 7, 26, 56, 0).toInstant(UTC);
PrometheusConnectorConfig config = getCommonConfig(prometheusHttpServer.resolve("/prometheus-data/prometheus-metr... |
public static boolean classInJarImplementsIface(java.io.File jar, String fqcn, Class xface) {
boolean ret = false;
java.net.URLClassLoader loader = null;
try {
loader = (URLClassLoader) ClassLoaderUtils.loadJar(jar);
if (xface.isAssignableFrom(Class.forName(fqcn, false, l... | @Test
public void testClassInJarImplementsIface() {
assertTrue(Reflections.classImplementsIface(aImplementation.class.getName(), aInterface.class));
assertFalse(Reflections.classImplementsIface(aImplementation.class.getName(), bInterface.class));
} |
public static ReferenceMap toReferenceMap(Map<String, Object> m) {
final ImmutableMap.Builder<String, Reference> mapBuilder = ImmutableMap.builder();
for (Map.Entry<String, Object> entry : m.entrySet()) {
final Object value = entry.getValue();
if (value instanceof Collection) {
... | @Test
public void toReferenceMap() {
final ImmutableMap<String, Object> map = ImmutableMap.<String, Object>builder()
.put("boolean", true)
.put("double", 2.0D)
.put("float", 1.0f)
.put("integer", 42)
.put("long", 10000000000L)
... |
protected static String clusterNameWithRouting(final String clusterName,
final String destinationColo,
final String masterColo,
final boolean defaultRoutingToMasterColo,
... | @Test
public static void testClusterNameWithRouting() throws Exception
{
String clusterNameWithRouting;
clusterNameWithRouting = D2Config.clusterNameWithRouting("clusterName",
"destinationColo",
... |
@Override
public String getAuthorizeUrl(Integer socialType, Integer userType, String redirectUri) {
// 获得对应的 AuthRequest 实现
AuthRequest authRequest = buildAuthRequest(socialType, userType);
// 生成跳转地址
String authorizeUri = authRequest.authorize(AuthStateUtils.createState());
r... | @Test
public void testGetAuthorizeUrl() {
try (MockedStatic<AuthStateUtils> authStateUtilsMock = mockStatic(AuthStateUtils.class)) {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(UserTypeEnum.class).getValue();
... |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testConsistentWithEqualsArrayOfArrayOfBytes() throws Exception {
FieldType fieldType = FieldType.array(FieldType.array(FieldType.BYTES));
Schema schema = Schema.of(Schema.Field.of("f1", fieldType));
RowCoder coder = RowCoder.of(schema);
List<byte[]> innerList1 = Collections.singleto... |
public static void defineParams(WebService.NewAction action, Languages languages) {
action.createParam(PARAM_QUALITY_PROFILE)
.setDescription("Quality profile name.")
.setRequired(true)
.setExampleValue("Sonar way");
action.createParam(PARAM_LANGUAGE)
.setDescription("Quality profile la... | @Test
public void define_ws_parameters() {
WebService.Context context = new WebService.Context();
WebService.NewController controller = context.createController("api/qualityprofiles");
WebService.NewAction newAction = controller.createAction("do").setHandler((request, response) -> {
});
Languages... |
boolean isWriteEnclosureForWriteField( byte[] str ) {
return ( meta.isEnclosureForced() && !meta.isPadded() )
|| isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( str );
} | @Test
public void testWriteEnclosureForWriteFieldWithEnclosureForced() {
TextFileOutputData data = new TextFileOutputData();
data.writer = new ByteArrayOutputStream();
data.binarySeparator = new byte[1];
TextFileOutputMeta meta = getTextFileOutputMeta();
meta.setEnclosureForced(true);
meta.set... |
public static Short min(Short a, Short b) {
return a <= b ? a : b;
} | @Test
void testMin() {
assertThat(summarize(-1000, 0, 1, 50, 999, 1001).getMin().shortValue())
.isEqualTo((short) -1000);
assertThat(summarize((int) Short.MIN_VALUE, -1000, 0).getMin().shortValue())
.isEqualTo(Short.MIN_VALUE);
assertThat(summarize(1, 8, 7, 6,... |
public boolean hasOobLog(String secretString) {
// making a blocking call to get result
Optional<PollingResult> result = sendPollingRequest(secretString);
if (result.isPresent()) {
// In the future we may refactor hasOobLog() to return finer grained info about what kind
// of oob is logged
... | @Test
public void isVulnerable_noLogRecordFetched_returnsFalse() throws IOException {
MockWebServer mockWebServer = new MockWebServer();
mockWebServer.enqueue(
new MockResponse().setResponseCode(HttpStatus.NOT_FOUND.code()).setBody(""));
client = new TcsClient(VALID_DOMAIN, VALID_PORT, mockWebServ... |
@Override
public long extract(final Object key, final GenericRow value) {
final String colValue = (String) extractor.extract(key, value);
try {
return timestampParser.parse(colValue);
} catch (final KsqlException e) {
throw new KsqlException("Unable to parse string timestamp."
+ " t... | @Test
public void shouldExtractTimestampFromStringWithFormat() throws ParseException {
// Given:
when(columnExtractor.extract(any(), any())).thenReturn("2010-Jan-11");
// When:
final long actualTime = extractor.extract(key, value);
final long expectedTime = new SimpleDateFormat(FORAMT).parse("20... |
@Override
public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException {
return getNextBufferOrEvent(false);
} | @Test
void testEmptyPull() throws IOException, InterruptedException {
final SingleInputGate inputGate1 = createInputGate(1);
TestInputChannel inputChannel1 = new TestInputChannel(inputGate1, 0, false, true);
inputGate1.setInputChannels(inputChannel1);
final SingleInputGate inputGate... |
@Override
public int hashCode() {
return Objects.hash(
Arrays.hashCode(salt),
Arrays.hashCode(storedKey),
Arrays.hashCode(serverKey),
iterations
);
} | @Test
public void testEqualsSameInstance() {
byte[] salt = {1, 2, 3};
byte[] storedKey = {4, 5, 6};
byte[] serverKey = {7, 8, 9};
int iterations = 1000;
ScramCredentialData data = new ScramCredentialData(salt, storedKey, serverKey, iterations);
// Test equals method... |
public ChannelFuture enqueue(QueuedCommand command, boolean rst) {
return enqueue(command);
} | @Test
@Disabled
void testChunk() throws Exception {
WriteQueue writeQueue = new WriteQueue();
// test deque chunk size
EmbeddedChannel embeddedChannel = new EmbeddedChannel();
TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel);
... |
@Override
public HttpResponseOutputStream<Metadata> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final DbxUserFilesRequests files = new DbxUserFilesRequests(session.getClient(file));
final UploadSessionStart... | @Test(expected = AccessDeniedException.class)
public void testWriteDesktopIni() throws Exception {
final DropboxWriteFeature write = new DropboxWriteFeature(session);
final TransferStatus status = new TransferStatus();
final byte[] content = RandomUtils.nextBytes(0);
status.setLength... |
@Override
public boolean test(Pickle pickle) {
if (expressions.isEmpty()) {
return true;
}
List<String> tags = pickle.getTags();
return expressions.stream()
.allMatch(expression -> expression.evaluate(tags));
} | @Test
void single_tag_predicate_does_not_match_pickle_with_no_tags() {
Pickle pickle = createPickleWithTags();
TagPredicate predicate = createPredicate("@FOO");
assertFalse(predicate.test(pickle));
} |
@Public
@Deprecated
public static ApplicationAttemptId toApplicationAttemptId(
String applicationAttemptIdStr) {
return ApplicationAttemptId.fromString(applicationAttemptIdStr);
} | @Test
@SuppressWarnings("deprecation")
void testInvalidAppattemptId() {
assertThrows(IllegalArgumentException.class, () -> {
ConverterUtils.toApplicationAttemptId("appattempt_1423221031460");
});
} |
public static void main(String[] args) throws Exception {
Arguments arguments = new Arguments();
CommandLine commander = new CommandLine(arguments);
try {
commander.parseArgs(args);
if (arguments.help) {
commander.usage(commander.getOut());
... | @Test
public void testMainGenerateDocs() throws Exception {
PrintStream oldStream = System.out;
try {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(baoStream));
Class argumentsClass =
Class.forNam... |
@Override
public SendResult send(final Message message) {
return send(message, this.rocketmqProducer.getSendMsgTimeout());
} | @Test
public void testSend_WithException() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
when(rocketmqProducer.send(any(Message.class), anyLong())).thenThrow(MQClientException.class);
try {
producer.send(producer.createBytesMessage("HELLO_TOPIC", ... |
public abstract ImmutableListMultimap<String, String> attributes(); | @Test
void attributes() {
final LDAPEntry entry = LDAPEntry.builder()
.dn("cn=jane,ou=people,dc=example,dc=com")
.base64UniqueId(Base64.encode("unique-id"))
.addAttribute("foo", "bar")
.build();
assertThat(entry.attributes().get("foo")... |
@Override
public Proxy find(final String target) {
for(java.net.Proxy proxy : selector.select(URI.create(target))) {
switch(proxy.type()) {
case DIRECT: {
return Proxy.DIRECT;
}
case HTTP: {
if(proxy.address(... | @Test
public void testSimpleExcluded() {
final DefaultProxyFinder proxy = new DefaultProxyFinder();
assertEquals(Proxy.Type.DIRECT, proxy.find("http://simple").getType());
assertEquals(Proxy.Type.DIRECT, proxy.find("sftp://simple").getType());
} |
@Override
public void open() throws Exception {
super.open();
collector = new TimestampedCollector<>(output);
context = new ContextImpl(userFunction);
internalTimerService =
getInternalTimerService(CLEANUP_TIMER_NAME, StringSerializer.INSTANCE, this);
} | @TestTemplate
void testContextCorrectRightTimestamp() throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new IntervalJoinOperator<>(
-1,
1,
true,
... |
@Override
public double getMean() {
if (values.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < values.length; i++) {
sum += values[i] * normWeights[i];
}
return sum;
} | @Test
public void expectNoOverflowForLowWeights() throws Exception {
final Snapshot scatteredSnapshot = new WeightedSnapshot(
WeightedArray(
new long[]{ 1, 2, 3 },
new double[]{ Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE }
)
)... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertLong() {
Column column = PhysicalColumn.builder().name("test").dataType(BasicType.LONG_TYPE).build();
BasicTypeDefine typeDefine = SqlServerTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName());
Asser... |
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smpp... | @Test
public void createSmppMessageFromDeliverSmWithPayloadInOptionalParameterShouldReturnASmppMessage() throws Exception {
DeliverSm deliverSm = new DeliverSm();
deliverSm.setSequenceNumber(1);
deliverSm.setCommandId(1);
deliverSm.setSourceAddr("1818");
deliverSm.setSourceAd... |
public static boolean isValidRule(AuthorityRule rule) {
return rule != null && !StringUtil.isBlank(rule.getResource())
&& rule.getStrategy() >= 0 && StringUtil.isNotBlank(rule.getLimitApp()) && RuleManager.checkRegexResourceField(rule);
} | @Test
public void testIsValidRule() {
AuthorityRule ruleA = new AuthorityRule();
AuthorityRule ruleB = null;
AuthorityRule ruleC = new AuthorityRule();
ruleC.setResource("abc");
AuthorityRule ruleD = new AuthorityRule();
ruleD.setResource("bcd").setLimitApp("abc");
... |
@Override
public void executeUpdate(final RegisterStorageUnitStatement sqlStatement, final ContextManager contextManager) {
checkDataSource(sqlStatement, contextManager);
Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.get... | @Test
void assertExecuteUpdateWithDuplicateStorageUnitNamesWithDataSourceContainedRule() {
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(contextManager.getMetaDataContexts()).thenReturn(mock(MetaDataContexts.class, RETURNS_DEEP_STUBS));
DataSourceMapper... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(true);
}
boolean result = true;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
ret... | @Test
void invokeArrayParamReturnTrue() {
FunctionTestUtil.assertResult(nnAllFunction.invoke(new Object[]{Boolean.TRUE, Boolean.TRUE}), true);
} |
public static String wrapWithMarkdownClassDiv(String html) {
return new StringBuilder()
.append("<div class=\"markdown-body\">\n")
.append(html)
.append("\n</div>")
.toString();
} | @Test
void testItalics() {
InterpreterResult result = md.interpret("This is *italics* text", null);
assertEquals(
wrapWithMarkdownClassDiv("<p>This is <em>italics</em> text</p>\n"),
result.message().get(0).getData());
} |
public void addRule(ElementSelector elementSelector, Supplier<Action> actionSupplier) {
Supplier<Action> existing = rules.get(elementSelector);
if (existing == null) {
rules.put(elementSelector, actionSupplier);
} else {
throw new IllegalStateException(elementSelector.t... | @Test
public void smokeII() throws Exception {
srs.addRule(new ElementSelector("a/b"), () -> new XAction());
Exception e = assertThrows(IllegalStateException.class, () -> {
srs.addRule(new ElementSelector("a/b"), () -> new YAction());
});
assertEquals("[a][b] already has... |
public RemotingCommand getConsumerListByGroup(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final RemotingCommand response =
RemotingCommand.createResponseCommand(GetConsumerListByGroupResponseHeader.class);
final GetConsumerListByGroupRequestH... | @Test
public void testGetConsumerListByGroup() throws RemotingCommandException {
GetConsumerListByGroupRequestHeader requestHeader = new GetConsumerListByGroupRequestHeader();
requestHeader.setConsumerGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GE... |
@POST
@Timed
@Path("tables/{idOrName}/purge")
@ApiOperation(value = "Purge Lookup Table Cache on the cluster-wide level")
@NoAuditEvent("Cache purge only")
@RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ)
public Map<String, CallResult<Void>> performPurge(
@ApiParam(name = "id... | @Test
public void performPurge_whenAllCallsSucceedThenResponseWithPerNodeDetailsReturned() throws Exception {
// given
when(nodeService.allActive()).thenReturn(nodeMap());
mock204Response("testName", "testKey", remoteLookupTableResource1);
mock204Response("testName", "testKey", remot... |
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
String json = reader.readLine();
log.debug("Converting response from influxDb: {}", json);
Map result = getResultObject... | @Test
public void deserialize() throws Exception {
List<InfluxDbResult> results = setupAllIntegers();
TypedInput input = new TypedByteArray(MIME_TYPE, EXAMPLE_ALL_INTEGERS.getBytes());
List<InfluxDbResult> result =
(List<InfluxDbResult>) influxDbResponseConverter.fromBody(input, List.class);
a... |
public static ServiceURI create(String uriStr) {
requireNonNull(uriStr, "service uri string is null");
if (uriStr.contains("[") && uriStr.contains("]")) {
// deal with ipv6 address
Splitter splitter = Splitter.on(CharMatcher.anyOf(",;"));
List<String> hosts = splitte... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testEmptyServiceUriString() {
ServiceURI.create("");
} |
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
try {
Metrics.summary(CONTENT_LENGTH_DISTRIBUTION_NAME, TRAFFIC_SOURCE_TAG, trafficSourceTag)
.record(requestContext.getLength());
Metrics.counter(IP_VERSION_METRIC, TRAFFIC_SOURCE_TAG, trafficSou... | @Test
void testFilter() throws Exception {
final RequestStatisticsFilter requestStatisticsFilter = new RequestStatisticsFilter(TrafficSource.WEBSOCKET);
final ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
when(requestContext.getLength()).thenReturn(-1);
when(requestC... |
void addRoutingProcessor(final String channel, final DynamicRouterProcessor processor) {
if (processors.putIfAbsent(channel, processor) != null) {
throw new IllegalArgumentException(
"Dynamic Router can have only one processor per channel; channel '"
... | @Test
void testAddRoutingProcessor() {
component.addRoutingProcessor(DYNAMIC_ROUTER_CHANNEL, processor);
assertEquals(processor, component.getRoutingProcessor(DYNAMIC_ROUTER_CHANNEL));
} |
static void dissectRemovePublicationCleanup(
final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
int absoluteOffset = offset;
absoluteOffset += dissectLogHeader(CONTEXT, REMOVE_PUBLICATION_CLEANUP, buffer, absoluteOffset, builder);
builder.append(": se... | @Test
void dissectRemovePublicationCleanup()
{
final int offset = 12;
internalEncodeLogHeader(buffer, offset, 22, 88, () -> 2_500_000_000L);
buffer.putInt(offset + LOG_HEADER_LENGTH, 42, LITTLE_ENDIAN);
buffer.putInt(offset + LOG_HEADER_LENGTH + SIZE_OF_INT, 11, LITTLE_ENDIAN);
... |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testCpuPercentageMemoryAbsoluteCpuNegative() throws Exception {
expectMissingResource("memory");
parseResourceConfigValue("-50% cpu, 1024 mb");
} |
public boolean getBoolean(@NotNull final String key) throws InvalidSettingException {
return Boolean.parseBoolean(getString(key));
} | @Test
public void testGetBoolean() throws InvalidSettingException {
String key = "SomeBoolean";
getSettings().setString(key, "false");
boolean expResult = false;
boolean result = getSettings().getBoolean(key);
Assert.assertEquals(expResult, result);
key = "something ... |
public static String getContent(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
throw new IllegalArgumentException("content does not contain separator");
}
return content.substring(index + 1);
} | @Test
void testGetContentFail() {
assertThrows(IllegalArgumentException.class, () -> {
String content = "aabbb";
ContentUtils.getContent(content);
});
} |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
@Category(ValidatesRunner.class)
public void testWindowedMapSideInput() {
final PCollectionView<Map<String, Integer>> view =
pipeline
.apply(
"CreateSideInput",
Create.timestamped(
TimestampedValue.of(KV.of("a", 1), new Instant(1)),
... |
public SchemaWriter(String typeName) {
this.typeName = typeName;
} | @Test
public void testSchemaWriter() {
SchemaWriter writer = new SchemaWriter("foo");
writer.writeBoolean(FieldKind.BOOLEAN.name(), true);
writer.writeArrayOfBoolean(FieldKind.ARRAY_OF_BOOLEAN.name(), null);
writer.writeInt8(FieldKind.INT8.name(), (byte) 0);
writer.writeArr... |
@Override
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
//Unlike when adding a producer, consumers must specify the destination at creation time, so we can rely on
//a destination being available to perform the authz check:
DestinationActio... | @Test(expected=UnauthorizedException.class)
public void testAddConsumerNotAuthorized() throws Exception {
String name = "myTopic";
ActiveMQDestination dest = new ActiveMQTopic(name);
Subject subject = new PermsSubject();
ConnectionContext context = createContext(subject);
Co... |
public StepDataInterface getStepData() {
return new DetectLastRowData();
} | @Test
public void testGetData() {
DetectLastRowMeta meta = new DetectLastRowMeta();
assertTrue( meta.getStepData() instanceof DetectLastRowData );
} |
public String getRole() {
return role;
} | @Test
public void testGetRole() {
// Test the getRole method
assertEquals("tc", event.getRole());
} |
public static <K, V> Cache<K, V> fromOptions(PipelineOptions options) {
return forMaximumBytes(
((long) options.as(SdkHarnessOptions.class).getMaxCacheMemoryUsageMb()) << 20);
} | @Test
public void testDefaultCache() throws Exception {
testCache(Caches.fromOptions(PipelineOptionsFactory.create()));
} |
@Override
public long skip(long n) {
long increase = Math.min(n, availableLong());
_currentOffset += increase;
return increase;
} | @Test
void testSkip() {
_dataBufferPinotInputStream.seek(1);
long skip = _dataBufferPinotInputStream.skip(2);
assertEquals(skip, 2);
assertEquals(_dataBufferPinotInputStream.getCurrentOffset(), 3);
} |
public List<String> getUuids() {
return this.stream().map(EnvironmentAgentConfig::getUuid).collect(toList());
} | @Test
void shouldGetEmptyListOfUUIDsWhenThereAreNoAgentsAssociatedWithEnvironment(){
List<String> uuids = envAgentsConfig.getUuids();
assertThat(uuids.size(), is(0));
} |
@Override
public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) {
List<Interval> intervals = Interval.group(history, start, end, dateField);
List<PurgeableAnalysisDto> result = new ArrayList<>();
for (Interval interval : intervals) {
appendSnapshotsToDelete(interval, result);
... | @Test
void shouldOnlyOneSnapshotPerInterval() {
Filter filter = new KeepOneFilter(DateUtils.parseDate("2011-03-25"), DateUtils.parseDate("2011-08-25"), Calendar.MONTH, "month");
List<PurgeableAnalysisDto> toDelete = filter.filter(Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2010-01-0... |
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) {
final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace();
final String importerDMNName = ((Definitions) importElement.getParent()).getName(... | @Test
void locateInNS() {
final Import i = makeImport("nsA", null, "m1");
final List<QName> available = Arrays.asList(new QName("nsA", "m1"),
new QName("nsA", "m2"),
new QName("nsB", "m3"));
... |
public HttpHeaders preflightResponseHeaders() {
if (preflightHeaders.isEmpty()) {
return EmptyHttpHeaders.INSTANCE;
}
final HttpHeaders preflightHeaders = new DefaultHttpHeaders();
for (Entry<CharSequence, Callable<?>> entry : this.preflightHeaders.entrySet()) {
f... | @Test
public void defaultPreflightResponseHeaders() {
final CorsConfig cors = forAnyOrigin().build();
assertThat(cors.preflightResponseHeaders().get(HttpHeaderNames.DATE), is(notNullValue()));
assertThat(cors.preflightResponseHeaders().get(HttpHeaderNames.CONTENT_LENGTH), is("0"));
} |
public <T extends Tuple> DataSource<T> tupleType(Class<T> targetType) {
Preconditions.checkNotNull(targetType, "The target type class must not be null.");
if (!Tuple.class.isAssignableFrom(targetType)) {
throw new IllegalArgumentException(
"The target type must be a subcl... | @Test
void testReturnType() {
CsvReader reader = getCsvReader();
DataSource<Item> items = reader.tupleType(Item.class);
assertThat(items.getType().getTypeClass()).isSameAs(Item.class);
} |
@Override
public String toString() {
StringBuilder sb = new StringBuilder("jmx:").append(getServerName());
if (!mQueryProps.isEmpty()) {
sb.append('?');
String delim = "";
for (Entry<String, String> entry : mQueryProps.entrySet()) {
sb.append(deli... | @Test
public void remote() {
assertEquals("jmx:service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi",
new JMXUriBuilder("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi").toString());
} |
static void validate(KafkaConsumer<byte[], byte[]> consumer, byte[] message, ConsumerRecords<byte[], byte[]> records) {
if (records.isEmpty()) {
consumer.commitSync();
throw new RuntimeException("poll() timed out before finding a result (timeout:[" + POLL_TIMEOUT_MS + "])");
}
... | @Test
@SuppressWarnings("unchecked")
public void shouldFailWhenReceivedMoreThanOneRecord() {
Iterator<ConsumerRecord<byte[], byte[]>> iterator = mock(Iterator.class);
ConsumerRecord<byte[], byte[]> record = mock(ConsumerRecord.class);
when(records.isEmpty()).thenReturn(false);
wh... |
@PublicAPI(usage = ACCESS)
public JavaClass importClass(Class<?> clazz) {
return getOnlyElement(importClasses(clazz));
} | @Test
public void class_has_source_of_import() throws Exception {
ArchConfiguration.get().setMd5InClassSourcesEnabled(true);
JavaClass clazzFromFile = new ClassFileImporter().importClass(ClassToImportOne.class);
Source source = clazzFromFile.getSource().get();
assertThat(source.getU... |
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException {
final List<MavenArtifact> result = new ArrayList<>();
try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
JsonParser ... | @Test
public void shouldProcessCorrectlyArtifactoryAnswerMisMatchSha1() throws IOException {
// Given
Dependency dependency = new Dependency();
dependency.setSha1sum("c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0e");
dependency.setSha256sum("512b4bf6927f4864acc419b8c5109c23361c30ed1f579817... |
public static SqlArgument of(final SqlType type) {
return new SqlArgument(type, null, null);
} | @Test
public void shouldThrowWhenLambdaNotPresentGettingLambda() {
final SqlArgument argument = SqlArgument.of(null, null);
final Exception e = assertThrows(
RuntimeException.class,
argument::getSqlLambdaOrThrow
);
assertThat(e.getMessage(), containsString("Was expecting lambda as a f... |
public boolean isActiveVersionPath(final String path) {
Matcher matcher = activeVersionPathPattern.matcher(path);
return matcher.find();
} | @Test
void assertIsActiveVersionPath() {
UniqueRuleItemNodePath uniqueRuleItemNodePath = new UniqueRuleItemNodePath(new RuleRootNodePath("foo"), "test_path");
assertTrue(uniqueRuleItemNodePath.isActiveVersionPath("/word1-/word2/rules/foo/test_path/active_version"));
} |
@Override
protected void doStart() throws Exception {
super.doStart();
LOG.debug("Creating connection to Azure ServiceBus");
client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(),
this::processMessage, this::processError);
... | @Test
void consumerFiltersApplicationPropertiesFromMessageHeaders() throws Exception {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) {
consumer.doStart();
verify(client).start();
verify(clientFactory).createServiceBusProcessorClient(any()... |
public void setSyncDelayMillis(long syncDelayMillis) {
this.syncDelayMillis = syncDelayMillis;
} | @Test
void testSetSyncDelayMillis() {
distroConfig.setSyncDelayMillis(syncDelayMillis);
assertEquals(syncDelayMillis, distroConfig.getSyncDelayMillis());
} |
public String getFormattedMessage() {
if (formattedMessage != null) {
return formattedMessage;
}
if (argumentArray != null) {
formattedMessage = MessageFormatter.arrayFormat(message, argumentArray).getMessage();
} else {
formattedMessage = message;
... | @Test
public void testNoFormattingWithArgs() {
String message = "testNoFormatting";
Throwable throwable = null;
Object[] argArray = new Object[] { 12, 13 };
LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray);
assertNull(event.formatted... |
@Override
public void trash(final Local file) throws LocalAccessDeniedException {
synchronized(NSWorkspace.class) {
if(log.isDebugEnabled()) {
log.debug(String.format("Move %s to Trash", file));
}
// Asynchronous operation. 0 if the operation is performed ... | @Test
public void testTrashOpenDirectoryEnumeration() throws Exception {
final Trash trash = new WorkspaceTrashFeature();
final SupportDirectoryFinder finder = new TemporarySupportDirectoryFinder();
final Local temp = finder.find();
final Local directory = LocalFactory.get(temp, UUI... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testPartitionedBucketString() throws Exception {
createPartitionedTable(spark, tableName, "bucket(5, data)");
SparkScanBuilder builder = scanBuilder();
BucketFunction.BucketString function = new BucketFunction.BucketString();
UserDefinedScalarFunc udf = toUDF(function, expr... |
@Override
public void handle(final RoutingContext routingContext) {
if (routingContext.request().isSSL()) {
final String indicatedServerName = routingContext.request().connection()
.indicatedServerName();
final String requestHost = routingContext.request().host();
if (indicatedServerNa... | @Test
public void shouldCheckOnlyIfTls() {
// Given:
when(routingContext.request()).thenReturn(serverRequest);
when(serverRequest.isSSL()).thenReturn(false);
// When:
new SniHandler().handle(routingContext);
// Then:
verify(routingContext, never()).fail(anyInt(), any());
verify(routi... |
public void setBuildFile(String buildFile) {
this.buildFile = buildFile;
} | @Test
public void rakeTaskShouldNormalizeBuildFile() {
RakeTask task = new RakeTask();
task.setBuildFile("pavan\\build.xml");
assertThat(task.arguments(), containsString("\"pavan/build.xml\""));
} |
@Override
public void execute(Context context) {
Collection<CeTaskMessages.Message> warnings = new ArrayList<>();
try (CloseableIterator<ScannerReport.AnalysisWarning> it = reportReader.readAnalysisWarnings()) {
it.forEachRemaining(w -> warnings.add(new CeTaskMessages.Message(w.getText(), w.getTimestamp... | @Test
public void execute_does_not_persist_warnings_from_reportReader_when_empty() {
reportReader.setScannerLogs(emptyList());
underTest.execute(new TestComputationStepContext());
verifyNoInteractions(ceTaskMessages);
} |
protected boolean identifierMatches(PropertyType suppressionEntry, Identifier identifier) {
if (identifier instanceof PurlIdentifier) {
final PurlIdentifier purl = (PurlIdentifier) identifier;
return suppressionEntry.matches(purl.toGav());
} else if (identifier instanceof CpeIden... | @Test
public void testCpeMatches() throws CpeValidationException, MalformedPackageURLException {
CpeIdentifier identifier = new CpeIdentifier("microsoft", ".net_framework", "4.5", Confidence.HIGHEST);
PropertyType cpe = new PropertyType();
cpe.setValue("cpe:/a:microsoft:.net_framework:4.5")... |
@Override
public void execute(ComputationStep.Context context) {
Metric qProfilesMetric = metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY);
new PathAwareCrawler<>(new QProfileAggregationComponentVisitor(qProfilesMetric))
.visit(treeRootHolder.getRoot());
} | @Test
public void nothing_to_add_when_no_files() {
ReportComponent project = ReportComponent.builder(PROJECT, PROJECT_REF).build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
assertThat(measureRepository.getAddedRawMeasures(PROJECT_REF)).isEmpty();
} |
public Set<String> indexNamesForStreamsInTimeRange(final Set<String> streamIds,
final TimeRange timeRange) {
Set<String> dataStreamIndices = streamIds.stream()
.filter(s -> s.startsWith(Stream.DATASTREAM_PREFIX))
.map(s -> s... | @Test
void returnsEmptySetIfNoIndicesFound() {
final IndexLookup sut = new IndexLookup(mock(IndexRangeService.class), mockStreamService(streamIds), mock(IndexRangeContainsOneOfStreams.class));
Set<String> result = sut.indexNamesForStreamsInTimeRange(streamIds, timeRangeWithNoIndexRanges);
as... |
public static UriTemplate create(String template, Charset charset) {
return new UriTemplate(template, true, charset);
} | @Test
void skipSlashes() {
String template = "https://www.example.com/{path}";
UriTemplate uriTemplate = UriTemplate.create(template, false, Util.UTF_8);
Map<String, Object> variables = new LinkedHashMap<>();
variables.put("path", "me/you/first");
String encoded = uriTemplate.expand(variables);
... |
@Override
public AllocatedSlotsAndReservationStatus removeSlots(ResourceID owner) {
final Set<AllocationID> slotsOfTaskExecutor = slotsPerTaskExecutor.remove(owner);
if (slotsOfTaskExecutor != null) {
final Collection<AllocatedSlot> removedSlots = new ArrayList<>();
final Ma... | @Test
void testRemoveSlots() {
final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool();
final ResourceID owner = ResourceID.generate();
final Collection<AllocatedSlot> slots = createAllocatedSlotsWithOwner(owner);
final AllocatedSlot otherSlot = createAllocatedSlot(... |
private static String transFromCamel(String key) {
Matcher matcher = PATTERN.matcher(key);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "." + matcher.group(0).toLowerCase(Locale.ROOT));
}
matcher.appendTail(sb);
... | @Test
public void testReadEnv() throws Exception {
testKey(CONFIG_KEY);
testKey(CONFIG_KEY.replace('.', '_'));
testKey(CONFIG_KEY.replace('.', '-'));
testKey(CONFIG_KEY.toLowerCase(Locale.ROOT).replace('.', '-'));
testKey(CONFIG_KEY.toLowerCase(Locale.ROOT).replace('.', '_'))... |
public Node pop() {
return nodes.poll();
} | @Test
void require_NameProviders_before_SearcherNodes() {
NameProvider nameProvider = createDummyNameProvider(100);
ComponentNode componentNode = new ComponentNode<>(createFakeComponentA("a"), 1);
addNodes(nameProvider, componentNode);
assertEquals(nameProvider, pop());
ass... |
public static boolean testURLPassesExclude(String url, String exclude) {
// If the url doesn't decode to UTF-8 then return false, it could be trying to get around our rules with nonstandard encoding
// If the exclude rule includes a "?" character, the url must exactly match the exclude rule.
// ... | @Test
public void testExcludeRules() {
assertFalse(AuthCheckFilter.testURLPassesExclude("blahblah/login.jsp", "login.jsp"));
assertTrue(AuthCheckFilter.testURLPassesExclude("login.jsp", "login.jsp"));
assertTrue(AuthCheckFilter.testURLPassesExclude("login.jsp?yousuck&blah", "login.jsp"));
... |
private static boolean visitTerminal(final SchemaVisitor visitor, final Schema schema, final Deque<Object> dq) {
SchemaVisitorAction action = visitor.visitTerminal(schema);
switch (action) {
case CONTINUE:
break;
case SKIP_SUBTREE:
throw new UnsupportedOperationException("Invalid action " + ... | @Test
void cloningError1() {
assertThrows(IllegalStateException.class, () -> {
// Visit Terminal with union
Schema recordSchema = new Schema.Parser().parse(
"{\"type\": \"record\", \"name\": \"R\", \"fields\":[{\"name\": \"f1\", \"type\": [\"int\", \"long\"]}]}");
new CloningVisitor(re... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetTransactionCount() throws Exception {
web3j.ethGetTransactionCount(
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
DefaultBlockParameterName.LATEST)
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\... |
public static YamlScalar asScalar(YamlNode node) {
if (node != null && !(node instanceof YamlScalar)) {
String nodeName = node.nodeName();
throw new YamlException(String.format("Child %s is not a scalar, it's actual type is %s", nodeName, node.getClass()));
}
return (Yam... | @Test(expected = YamlException.class)
public void asScalarThrowsIfNonScalarPassed() {
YamlNode genericNode = new YamlMappingImpl(null, "mapping");
YamlUtil.asScalar(genericNode);
} |
@Override public String service() {
return DubboParser.service(invoker);
} | @Test void service() {
when(invocation.getInvoker()).thenReturn(invoker);
when(invoker.getUrl()).thenReturn(url);
assertThat(request.service())
.isEqualTo("brave.dubbo.GreeterService");
} |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReturnTimeUnitAsYearsWhenDurationIsLargerThan3Years() throws Exception {
assertEquals(TimeConverter.OVER_X_YEARS_AGO.argument(3), timeConverter
.getConvertedTime(3 * 365 * TimeConverter.DAY_IN_SECONDS + 2 * TimeConverter.DAY_IN_SECONDS));
} |
@Override
public long getVersion() {
return record.getVersion();
} | @Test
public void test_getVersion() {
assertEquals(0, view.getVersion());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.