focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public TpcEngineBuilder setReactorCount(int reactorCount) {
this.reactorCount = checkPositive(reactorCount, "reactorCount");
return this;
} | @Test
public void test_setReactorCountWhenZero() {
TpcEngineBuilder builder = new TpcEngineBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.setReactorCount(0));
} |
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException {
ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null"));
if (null == value) {
return convertNullValue(co... | @Test
void assertConvertNumberValueError() {
assertThrows(UnsupportedDataTypeConversionException.class, () -> ResultSetUtils.convertValue(1, Date.class));
} |
public Map<String, Object> getNodeMetrics(String node) {
Map<String, Object> metrics = new HashMap<>();
Request nodeStatRequest = new Request("GET", "_nodes/" + node + "/stats");
final DocumentContext nodeContext = getNodeContextFromRequest(node, nodeStatRequest);
if (Objects.nonNull(n... | @Test
public void getNodeMetrics() {
Map<String, Object> nodeMetrics = collector.getNodeMetrics(NODENAME);
assertThat(nodeMetrics.get("cpu_load")).isEqualTo(26.4873046875);
assertThat(nodeMetrics.get("disk_free")).isEqualTo(572.1824f);
String[] allMetrics = Arrays.stream(NodeStatMetr... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest req) {
var certs = req.getClientCertificateChain();
log.fine(() -> "Certificate chain contains %d elements".formatted(certs.size()));
if (certs.isEmpty()) {
log.fine("Missing client certificate");
re... | @Test
void accepts_client_with_valid_certificate() {
var req = FilterTestUtils.newRequestBuilder()
.withMethod(Method.POST)
.withClientCertificate(FEED_CERT)
.build();
var responseHandler = new MockResponseHandler();
newFilterWithClientsConfig(... |
@SuppressWarnings("unchecked")
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
return register(MetricName.build(name), metric);
} | @Test
public void registeringACounterTriggersANotification() throws Exception {
assertThat(registry.register(THING, counter))
.isEqualTo(counter);
verify(listener).onCounterAdded(THING, counter);
} |
public void transmit(final int msgTypeId, final DirectBuffer srcBuffer, final int srcIndex, final int length)
{
checkTypeId(msgTypeId);
checkMessageLength(length);
final AtomicBuffer buffer = this.buffer;
long currentTail = buffer.getLong(tailCounterIndex);
int recordOffset ... | @Test
void shouldTransmitIntoUsedBuffer()
{
final long tail = RECORD_ALIGNMENT * 3;
final int recordOffset = (int)tail;
final int length = 8;
final int recordLength = length + HEADER_LENGTH;
final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);
w... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testInflightFetchOnPendingPartitions() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
subscriptions.markPendingRevocation(singleton(tp0));
client.prepareResponse(fullFetchResponse(tidp... |
@Override
public String toString() {
return getClass().getSimpleName() + "[application=" + getApplication() + ", name="
+ getName() + ", storageName=" + getStorageName() + ", startDate=" + getStartDate()
+ ", childCounterName=" + getChildCounterName() + ", " + requests.size()
+ " requests, " + (errors ==... | @Test
public void testToString() {
counter.addRequest("test toString", 100, 50, 50, false, 1000);
final String string = counter.toString();
assertNotNull("toString not null", string);
assertFalse("toString not empty", string.isEmpty());
final String string2 = new Counter(Counter.ERROR_COUNTER_NAME, null).toS... |
static <T extends Type> String encodeDynamicArray(DynamicArray<T> value) {
int size = value.getValue().size();
String encodedLength = encode(new Uint(BigInteger.valueOf(size)));
String valuesOffsets = encodeArrayValuesOffsets(value);
String encodedValues = encodeArrayValues(value);
... | @SuppressWarnings("unchecked")
@Test
public void testArrayOfStrings() {
DynamicArray<Utf8String> array =
new DynamicArray<>(
new Utf8String(
"This string value is extra long so that it "
+ "re... |
@Override
public Optional<Integer> extractIndexNumber(final String indexName) {
final int beginIndex = indexPrefixLength(indexName);
if (indexName.length() < beginIndex) {
return Optional.empty();
}
final String suffix = indexName.substring(beginIndex);
try {
... | @Test
public void testExtractIndexNumber() {
assertThat(mongoIndexSet.extractIndexNumber("graylog_0")).contains(0);
assertThat(mongoIndexSet.extractIndexNumber("graylog_4")).contains(4);
assertThat(mongoIndexSet.extractIndexNumber("graylog_52")).contains(52);
assertThat(mongoIndexSet... |
public LoggerContext apply(LogLevelConfig logLevelConfig, Props props) {
if (!ROOT_LOGGER_NAME.equals(logLevelConfig.getRootLoggerName())) {
throw new IllegalArgumentException("Value of LogLevelConfig#rootLoggerName must be \"" + ROOT_LOGGER_NAME + "\"");
}
LoggerContext rootContext = getRootContext(... | @Test
public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_ROOT_LOGGER_NAME_of_LogBack() {
LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build();
assertThatThrownBy(() -> underTest.apply(logLevelConfig, props))
.isInstanceOf(IllegalArgumentException.class)... |
@Nonnull
public static <T> Sink<T> list(@Nonnull String listName) {
return fromProcessor("listSink(" + listName + ')', writeListP(listName));
} | @Test
public void list_byRef() {
// Given
populateList(srcList);
// When
Sink<Object> sink = Sinks.list(sinkList);
// Then
p.readFrom(Sources.list(srcList)).writeTo(sink);
execute();
assertEquals(itemCount, sinkList.size());
} |
@Override
public void run() {
try (DbSession dbSession = dbClient.openSession(false)) {
int size = dbClient.ceQueueDao().countByStatus(dbSession, CeQueueDto.Status.PENDING);
metrics.setNumberOfPendingTasks(size);
}
} | @Test
public void run_setsValueInMetricsBasedOnValueReturnedFromDatabase() {
NumberOfTasksInQueueTask task = new NumberOfTasksInQueueTask(dbClient, metrics, config);
when(dbClient.ceQueueDao()).thenReturn(ceQueueDao);
when(ceQueueDao.countByStatus(any(), any())).thenReturn(10);
task.run();
verif... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize"));
} | @Test
@Ignore
public void testVersioning() throws Exception {
final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(session)).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStat... |
static SpecificData getModelForSchema(Schema schema) {
final Class<?> clazz;
if (schema != null && (schema.getType() == Schema.Type.RECORD || schema.getType() == Schema.Type.UNION)) {
clazz = SpecificData.get().getClass(schema);
} else {
return null;
}
// If clazz == null, the underlyi... | @Test
public void testModelForSpecificRecordWithLogicalTypes() {
SpecificData model = AvroRecordConverter.getModelForSchema(LogicalTypesTest.SCHEMA$);
// Test that model is generated correctly
Collection<Conversion<?>> conversions = model.getConversions();
assertEquals(conversions.size(), 3);
ass... |
@Override
public EueWriteFeature.Chunk upload(final Path file, Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback prompt) throws BackgroundException {
if(status.getLength() >= threshold) ... | @Test
public void testUploadLargeFileInChunks() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final EueThresholdUploadService service = new EueThresholdUploadService(session, fileid, VaultRegistry.DISABLED);
final Path container = new EueDirector... |
public void execute() {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
.visit(treeRootHolder.getReportTreeRoot());
} | @Test
public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_of_a_single_line() {
TextBlock original = new TextBlock(1, 1);
duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(2, 2));
underTest.execute();
assertRawMeasureValue(FILE_1_REF, DUPLICATED_L... |
public static <T, R extends Type<T>, E extends Type<T>> List<E> typeMap(
List<List<T>> input, Class<E> outerDestType, Class<R> innerType) {
List<E> result = new ArrayList<>();
try {
Constructor<E> constructor =
outerDestType.getDeclaredConstructor(Class.class,... | @SuppressWarnings("unchecked")
@Test
public void testTypeMapNested() {
List<BigInteger> innerList1 = Arrays.asList(BigInteger.valueOf(1), BigInteger.valueOf(2));
List<BigInteger> innerList2 = Arrays.asList(BigInteger.valueOf(3), BigInteger.valueOf(4));
final List<List<BigInteger>> input... |
@Override
public BackgroundException map(final ApiException failure) {
final StringBuilder buffer = new StringBuilder();
if(StringUtils.isNotBlank(failure.getMessage())) {
for(String s : StringUtils.split(failure.getMessage(), ",")) {
this.append(buffer, LocaleFactory.loc... | @Test
public void testEnhancedStatus() {
final BackgroundException failure = new EueExceptionMappingService().map(new ApiException(404, "",
Collections.singletonMap("X-UI-ENHANCED-STATUS", Collections.singletonList("NOT_FOUND")), ""));
assertTrue(failure instanceof NotfoundException)... |
@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 shouldConvertZhFromDecimal() {
final String result = udf.chr(22909);
assertThat(result, is("好"));
} |
@Override
protected ExecuteContext doBefore(ExecuteContext context) {
ClientMessage clientMessage = (ClientMessage) context.getArguments()[0];
String database = getDataBaseInfo(context).getDatabaseName();
handleWriteOperationIfWriteDisabled(clientMessage.description(), database,
... | @Test
public void testDoBefore() throws Exception {
// the database write prohibition switch is disabled
globalConfig.setEnableMySqlWriteProhibition(false);
context = ExecuteContext.forMemberMethod(clientMock, methodMock, argument, null, null);
interceptor.before(context);
As... |
public static Map<String, Set<String>> parseTableExpressionWithSchema(final ShardingSphereDatabase database, final Collection<SchemaTable> schemaTables) {
Collection<String> systemSchemas = DatabaseTypedSPILoader.getService(DialectSystemDatabase.class, database.getProtocolType()).getSystemSchemas();
if ... | @Test
void assertParseTableExpression() {
Map<String, ShardingSphereSchema> schemas = new HashMap<>(2, 1F);
schemas.put("public", mockedPublicSchema());
schemas.put("test", mockedTestSchema());
ShardingSphereDatabase database = new ShardingSphereDatabase("sharding_db", TypedSPILoader... |
@Override
public <K, V> void forward(final K key, final V value) {
throw new UnsupportedOperationException("StateStores can't access forward.");
} | @Test
public void shouldThrowOnForwardWithTo() {
assertThrows(UnsupportedOperationException.class, () -> context.forward("key", "value", To.all()));
} |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldThrowWhenCreateAsSelectExistingStreamWithoutWritePermissionsDenied() {
// Given:
givenTopicAccessDenied(AVRO_TOPIC, AclOperation.WRITE);
final Statement statement = givenStatement(String.format(
"CREATE STREAM %s AS SELECT * FROM %s;", AVRO_STREAM_TOPIC, KAFKA_STREAM_TOPIC)... |
public List<PartitionStatisticsFile> partitionStatisticsFiles() {
return partitionStatisticsFiles;
} | @Test
public void testParsePartitionStatisticsFiles() throws Exception {
String data = readTableMetadataInputFile("TableMetadataPartitionStatisticsFiles.json");
TableMetadata parsed = TableMetadataParser.fromJson(data);
assertThat(parsed.partitionStatisticsFiles())
.hasSize(1)
.first()
... |
@NonNull
@Override
public String getId() {
return ID;
} | @Test
public void getBitbucketScm() throws UnirestException {
Map r = new RequestBuilder(baseUrl)
.crumb(crumb)
.status(200)
.jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(), authenticatedUser.getId()))
.post("/organizations/jenkins/s... |
@Override
public int run(String[] args) throws Exception {
Options opts = new Options();
opts.addOption("lnl", LIST_LABELS_CMD, false,
"List cluster node-label collection");
opts.addOption("lna", LIST_CLUSTER_ATTRIBUTES, false,
"List cluster node-attribute collection");
opts.addOp... | @Test
public void testGetClusterNodeLabels() throws Exception {
when(client.getClusterNodeLabels()).thenReturn(
Arrays.asList(NodeLabel.newInstance("label1"),
NodeLabel.newInstance("label2")));
ClusterCLI cli = createAndGetClusterCLI();
int rc =
cli.run(new String[] { Clus... |
@SuppressWarnings("rawtypes")
public Collection<RuleConfiguration> swapToRuleConfigurations(final Collection<RepositoryTuple> repositoryTuples) {
if (repositoryTuples.isEmpty()) {
return Collections.emptyList();
}
Collection<RuleConfiguration> result = new LinkedList<>();
... | @Test
void assertSwapToRuleConfigurations() {
assertTrue(new RepositoryTupleSwapperEngine().swapToRuleConfigurations(Collections.singleton(new RepositoryTuple("/rules/leaf/versions/0", "value: foo"))).isEmpty());
} |
public static <T> TimeLimiterOperator<T> of(TimeLimiter timeLimiter) {
return new TimeLimiterOperator<>(timeLimiter);
} | @Test
public void doNotTimeoutUsingMono() {
given(timeLimiter.getTimeLimiterConfig())
.willReturn(toConfig(Duration.ofMinutes(1)));
given(helloWorldService.returnHelloWorld())
.willReturn("Hello world");
Mono<?> mono = Mono.fromCallable(helloWorldService::returnHello... |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testAndOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg =
builder
.startAnd()
.equals("salary", PredicateLeaf.Type.LONG, 3000L)
.equals("salary", PredicateLeaf.Type.LONG, 4000L)
.end()
... |
@NonNull
@Override
public String getId() {
return ID;
} | @Test
public void getRepositoriesWithCredentialId() throws IOException, UnirestException {
String credentialId = createCredential(BitbucketCloudScm.ID);
Map repoResp = new RequestBuilder(baseUrl)
.crumb(crumb)
.status(200)
.jwtToken(getJwtToken(j.jenki... |
public static Socket acceptWithoutTimeout(ServerSocket serverSocket) throws IOException {
Preconditions.checkArgument(
serverSocket.getSoTimeout() == 0, "serverSocket SO_TIMEOUT option must be 0");
while (true) {
try {
return serverSocket.accept();
... | @Test
void testAcceptWithoutTimeoutSuppressesTimeoutException() throws IOException {
// Validates that acceptWithoutTimeout suppresses all SocketTimeoutExceptions
Socket expected = new Socket();
ServerSocket serverSocket =
new ServerSocket() {
private int ... |
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
// TODO do not load everything in memory. Db rows should be scrolled.
List<IndexPermissions> authorizations = getAllAuthorizations();
Stream<AuthorizationScope> scopes = getScopes(uninitializedIndexTypes);
index(authorizati... | @Test
public void indexOnStartup_grants_access_to_anybody_on_view() {
PortfolioDto view = createAndIndexPortfolio();
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
indexOnStartup();
verifyAnyoneAuthorized(view);
verifyAuthorized(view, user);
verifyAuth... |
static ArgumentParser argParser() {
ArgumentParser parser = ArgumentParsers
.newArgumentParser("producer-performance")
.defaultHelp(true)
.description("This tool is used to verify the producer performance. To enable transactions, " +
"you c... | @Test
public void testNoTransactionRelatedConfigs() throws IOException, ArgumentParserException {
ArgumentParser parser = ProducerPerformance.argParser();
String[] args = new String[]{
"--topic", "Hello-Kafka",
"--num-records", "5",
"--throughput", "100",
... |
@Override
public List<TaskProperty> getPropertiesForDisplay() {
return new ArrayList<>();
} | @Test
public void shouldReturnEmptyPropertiesForDisplay() {
assertThat(new NullTask().getPropertiesForDisplay().isEmpty(), is(true));
} |
@Override
public synchronized Future<RecordMetadata> send(ProducerRecord<K, V> record) {
return send(record, null);
} | @Test
@SuppressWarnings("unchecked")
public void shouldThrowClassCastException() {
try (MockProducer<Integer, String> customProducer = new MockProducer<>(true, new IntegerSerializer(), new StringSerializer())) {
assertThrows(ClassCastException.class, () -> customProducer.send(new ProducerRec... |
public static void copyBody(Message source, Message target) {
// Preserve the DataType if both messages are DataTypeAware
if (source.hasTrait(MessageTrait.DATA_AWARE)) {
target.setBody(source.getBody());
target.setPayloadForTrait(MessageTrait.DATA_AWARE,
sourc... | @Test
void shouldCopyBodyIfBothDataTypeAwareWithoutDataTypeSet() {
Object body = new Object();
DefaultMessage m1 = new DefaultMessage((Exchange) null);
m1.setBody(body, (DataType) null);
DefaultMessage m2 = new DefaultMessage((Exchange) null);
copyBody(m1, m2);
assert... |
@Override
public Mono<GetCurrencyConversionsResponse> getCurrencyConversions(final GetCurrencyConversionsRequest request) {
AuthenticationUtil.requireAuthenticatedDevice();
final CurrencyConversionEntityList currencyConversionEntityList = currencyManager
.getCurrencyConversions()
.orElseThrow... | @Test
void testUnavailable() {
when(currencyManager.getCurrencyConversions()).thenReturn(Optional.empty());
assertStatusException(Status.UNAVAILABLE, () -> authenticatedServiceStub().getCurrencyConversions(
GetCurrencyConversionsRequest.newBuilder().build()));
} |
@Override
public void subscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("subscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("subscribe listener == null");
}
if (logger... | @Test
void testSubscribe() {
// check parameters
try {
abstractRegistry.subscribe(testUrl, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof IllegalArgumentException);
}
// check parameters
try {
... |
public static String formatDA(TimeZone tz, Date date) {
return formatDA(tz, date, new StringBuilder(8)).toString();
} | @Test
public void testFormatDA() {
assertEquals("19700101", DateUtils.formatDA(tz, new Date(0)));
} |
public static FormationFilterDefinition parseFormationFilterDefinition(String definition) {
String[] tokens = definition.split(",");
Distance dist = Distance.ofNauticalMiles(parseDouble(tokens[0]));
Duration time = Duration.ofSeconds(parseLong(tokens[1]));
boolean log = Boolean.parseBo... | @Test
public void canParseOneDefinition() {
String singleDef = "0.85,92,true";
FormationFilterDefinition def = parseFormationFilterDefinition(singleDef);
assertThat(def.timeRequirement, is(Duration.ofSeconds(92)));
assertThat(def.proximityRequirement, is(Distance.ofNauticalMiles(0.... |
public static List<String> getFieldNames(Class<? extends Enum<?>> clazz) {
if(null == clazz){
return null;
}
final List<String> names = new ArrayList<>();
final Field[] fields = ReflectUtil.getFields(clazz);
String name;
for (Field field : fields) {
name = field.getName();
if (field.getType().isEnu... | @Test
public void getFieldNamesTest() {
List<String> names = EnumUtil.getFieldNames(TestEnum.class);
assertTrue(names.contains("type"));
assertTrue(names.contains("name"));
} |
public void append(long offset, int position) {
lock.lock();
try {
if (isFull())
throw new IllegalArgumentException("Attempt to append to a full index (size = " + entries() + ").");
if (entries() == 0 || offset > lastOffset) {
log.trace("Adding in... | @Test
public void appendOutOfOrder() {
index.append(51, 0);
assertThrows(InvalidOffsetException.class, () -> index.append(50, 1));
} |
public static boolean metadataChanged(Cluster previous, Cluster current) {
// Broker has changed.
Set<Node> prevNodeSet = new HashSet<>(previous.nodes());
if (prevNodeSet.size() != current.nodes().size()) {
return true;
}
current.nodes().forEach(prevNodeSet::remove);
if (!prevNodeSet.isEmp... | @Test
public void testMetadataChanged() {
Node[] nodesWithOrder1 = {NODE_0, NODE_1};
Node[] nodesWithOrder2 = {NODE_1, NODE_0};
Node[] nodes2 = {NODE_0, NODE_2};
// Cluster 1 just has one partition
PartitionInfo t0p0 = new PartitionInfo(TOPIC0, 0, NODE_0, nodesWithOrder1, nodesWithOrder2);
Par... |
public void verify(CvCertificate cert) {
final Deque<CvCertificate> chain = getTrustChain(cert);
// Only CVCA has domain parameters
final ECDomainParameters params = chain.getLast().getBody().getPublicKey().getParams();
while (!chain.isEmpty()) {
final CvCertificate signer ... | @Test
public void shouldVerifyIfRootIsTrustedWithIntermediate() throws Exception {
certificateRepo.save(loadCvCertificate("rdw/acc/cvca.cvcert", true));
certificateRepo.save(loadCvCertificate("rdw/acc/dvca.cvcert", false));
certificateRepo.flush();
service.verify(readCvCertificate("r... |
@Override
public ObjectNode encode(MappingAddress address, CodecContext context) {
EncodeMappingAddressCodecHelper encoder =
new EncodeMappingAddressCodecHelper(address, context);
return encoder.encode();
} | @Test
public void ipv4MappingAddressTest() {
MappingAddress address = MappingAddresses.ipv4MappingAddress(IPV4_PREFIX);
ObjectNode result = addressCodec.encode(address, context);
assertThat(result, matchesMappingAddress(address));
} |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testDeadzone() {
int[][] qData = new int[][]{
// / A B C
{ 100, 40, 40, 20 }, // abs
{ 100, 100, 100, 100 }, // maxCap
{ 100, 39, 43, 21 }, // used
{ 10, 10, 0, 0 }, // pending
{ 0, 0, 0, 0 }, // reserved
{ 3, 1, 1, 1 }, // apps... |
protected boolean isIpAddress(String field, FieldPresence presence) {
return isIpAddress(object, field, presence);
} | @Test
public void isIpAddress() {
assertTrue("is not proper ip", cfg.isIpAddress(IP, MANDATORY));
assertTrue("is not proper ip", cfg.isIpAddress(IP, OPTIONAL));
assertTrue("is not proper ip", cfg.isIpAddress("none", OPTIONAL));
assertTrue("did not detect missing ip",
... |
public Book get(long bookId) throws BookNotFoundException {
if (!collection.containsKey(bookId)) {
throw new BookNotFoundException("Not found book with id: " + bookId);
}
// return copy of the book
return new Book(collection.get(bookId));
} | @Test
void testDefaultVersionRemainsZeroAfterAdd() throws BookNotFoundException {
var book = bookRepository.get(bookId);
assertEquals(0, book.getVersion());
} |
@Override
public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
@Nullable String projectName) {
String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto);
String url = requireNonNull(... | @Test
void createProjectAndBindToDevOpsPlatform_whenRepositoryNotFound_shouldThrow() {
mockPatForUser();
when(azureDevOpsHttpClient.getRepo(AZURE_DEVOPS_URL, USER_PAT, DEVOPS_PROJECT_ID, REPOSITORY_NAME))
.thenThrow(new AzureDevopsServerException(404, "Problem fetching repository from AzureDevOps"));
... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseLiteralStepParameter() {
StringParameter bar = StringParameter.builder().name("bar").value("test ${foo}").build();
paramEvaluator.parseStepParameter(
Collections.emptyMap(),
Collections.emptyMap(),
Collections.singletonMap("foo", StringParameter.builder().val... |
@Override
public <T extends BaseRedisNodes> T getRedisNodes(org.redisson.api.redisnode.RedisNodes<T> nodes) {
if (nodes.getClazz() == RedisSingle.class) {
if (config.isSentinelConfig() || config.isClusterConfig()) {
throw new IllegalArgumentException("Can't be used in non Redis s... | @Test
public void testSave() throws InterruptedException {
Instant s2 = Instant.now();
Thread.sleep(1000);
RedisSingle nodes = redisson.getRedisNodes(RedisNodes.SINGLE);
RedisMaster node = nodes.getInstance();
Instant time1 = node.getLastSaveTime();
assertThat(time1)... |
@Override
protected IRODSFileSystemAO connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
try {
final IRODSFileSystem fs = this.configure(IRODSFileSystem.instance());
final IRODSAccessObject... | @Test
public void testConnect() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/iRODS (iPlant Collabo... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void longlivedLightPortalLocalhost() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaims("stevehu@gmail.com", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e73", Arrays.asList("portal.r", "portal.w"), "user lightapi.net admin");
claims.setExpirationTimeMinutesInTheFuture(5256... |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testReplaceValueTTL() throws InterruptedException {
RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"), Duration.ofSeconds(1));
Thread.sleep(1000);
SimpleValue res = map.repl... |
@Override
public void put(final Bytes rawBaseKey,
final byte[] value) {
final long timestamp = baseKeySchema.segmentTimestamp(rawBaseKey);
observedStreamTime = Math.max(observedStreamTime, timestamp);
final long segmentId = segments.segmentId(timestamp);
final S s... | @Test
public void shouldFetchSessionForTimeRange() {
// Only for TimeFirstSessionKeySchema schema
if (!(getBaseSchema() instanceof TimeFirstSessionKeySchema)) {
return;
}
final String keyA = "a";
final String keyB = "b";
final String keyC = "c";
f... |
@Override
public String toString() {
// Add the options that we received from deserialization
SortedMap<String, Object> sortedOptions = new TreeMap<>(jsonOptions);
// Override with any programmatically set options.
for (Map.Entry<String, BoundValue> entry : options.entrySet()) {
sortedOptions.pu... | @Test
public void testToString() throws Exception {
// TODO: Java core test failing on windows, https://github.com/apache/beam/issues/20485
assumeFalse(SystemUtils.IS_OS_WINDOWS);
ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap());
StringWithDefault proxy = handler.as(Strin... |
public static GcsPath fromComponents(@Nullable String bucket, @Nullable String object) {
return new GcsPath(null, bucket, object);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidObject_cr() {
GcsPath.fromComponents(null, "a\rb");
} |
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder)
throws CoderException {
if (value == null) {
return noopMutationDetector();
} else {
return new CodedValueMutationDetector<>(value, coder);
}
} | @Test
public void testImmutableIterable() throws Exception {
Iterable<Integer> value = FluentIterable.from(Arrays.asList(1, 2, 3, 4)).cycle().limit(50);
MutationDetector detector =
MutationDetectors.forValueWithCoder(value, IterableCoder.of(VarIntCoder.of()));
detector.verifyUnmodified();
} |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_serializable_complex_object_with_non_serializable_nested_object() {
Map<String, List<NonSerializableObject>> map = new LinkedHashMap<>();
map.put("key1", Lists.newArrayList(new NonSerializableObject("name1")));
map.put("key2", Lists.newArrayList(
ne... |
static SortKey[] rangeBounds(
int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) {
// sort the keys first
Arrays.sort(samples, comparator);
int numCandidates = numPartitions - 1;
SortKey[] candidates = new SortKey[numCandidates];
int step = (int) Math.ceil((double) sample... | @Test
public void testRangeBoundsNonDivisible() {
// step is 3 = ceiling(11/4)
assertThat(
SketchUtil.rangeBounds(
4,
SORT_ORDER_COMPARTOR,
new SortKey[] {
CHAR_KEYS.get("a"),
CHAR_KEYS.get("b"),
... |
@Override
public <T extends Notification<?>> Flowable<T> subscribe(
Request request, String unsubscribeMethod, Class<T> responseType) {
// We can't use usual Observer since we can call "onError"
// before first client is subscribed and we need to
// preserve it
BehaviorSu... | @Test
public void testPropagateSubscriptionEvent() throws Exception {
CountDownLatch eventReceived = new CountDownLatch(1);
CountDownLatch disposed = new CountDownLatch(1);
AtomicReference<NewHeadsNotification> actualNotificationRef = new AtomicReference<>();
runAsync(
... |
@Override
public Num calculate(BarSeries series, Position position) {
return calculateProfit(series, position);
} | @Test
public void calculateWithWinningLongPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, ser... |
@Override
public void upgrade() {
if (clusterConfigService.get(V20161216123500_Succeeded.class) != null) {
return;
}
// The default index set must have been created first.
checkState(clusterConfigService.get(DefaultIndexSetCreated.class) != null, "The default index set h... | @Test
public void upgradeFailsIfDefaultIndexSetHasNotBeenCreated() {
when(clusterConfigService.get(DefaultIndexSetCreated.class)).thenReturn(null);
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("The default index set hasn't been created yet. This is a... |
public void initDefaultMasterKey() {
String defaultMasterKeySpec = Config.default_master_key;
keysLock.writeLock().lock();
try {
if (defaultMasterKeySpec.isEmpty()) {
if (idToKey.size() != 0) {
LOG.error("default_master_key removed in config");
... | @Test
public void testInitDefaultMasterKey() {
new MockUp<System>() {
@Mock
public void exit(int value) {
throw new RuntimeException(String.valueOf(value));
}
};
String oldConfig = Config.default_master_key;
try {
Config... |
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
} | @Test
public void when_addNonexistentResourceWithPathAndId_then_throwsException() {
// Given
String id = "exist";
String path = Paths.get("/i/do/not/" + id).toString();
// Then
expectedException.expect(JetException.class);
expectedException.expectMessage("Not an exis... |
@Override
public byte[] get(byte[] key) {
return read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key);
} | @Test
public void testGeo() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson));
redisTemplate.afterPropertiesSet();
String key = "test_geo_key";
Point point = new Point(116.401001... |
public InnerCNode getTree() throws CodegenRuntimeException {
try {
if (root == null) parse();
} catch (DefParserException | IOException e) {
throw new CodegenRuntimeException("Error parsing or reading config definition." + e.getMessage(), e);
}
return root;
} | @Test
void testEnum() {
StringBuilder sb = createDefTemplate();
sb.append("enum1 enum {A,B} default=A\n");
sb.append("enum2 enum {A, B} default=A\n");
sb.append("enum3 enum { A, B} default=A\n");
sb.append("enum4 enum { A, B } default=A\n");
sb.append("enum5 enum { A ... |
public Flowable<String> getKeys() {
return getKeysByPattern(null);
} | @Test
public void testMassDelete() {
RBucketRx<String> bucket = redisson.getBucket("test");
sync(bucket.set("someValue"));
RMapRx<String, String> map = redisson.getMap("map2");
sync(map.fastPut("1", "2"));
Assertions.assertEquals(2, sync(redisson.getKeys().delete("test", "ma... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setMyDescription() {
BaseResponse response = bot.execute(new SetMyDescription().description("desc").languageCode("en"));
assertTrue(response.isOk());
GetMyDescriptionResponse descResponse = bot.execute(new GetMyDescription().languageCode("en"));
assertTrue(descResp... |
public static <T> Supplier<T> recover(Supplier<T> supplier,
Predicate<T> resultPredicate, UnaryOperator<T> resultHandler) {
return () -> {
T result = supplier.get();
if(resultPredicate.test(result)){
return resultHandler.apply(result);
}
re... | @Test
public void shouldRecoverSupplierFromException() {
Supplier<String> supplier = () -> {
throw new RuntimeException("BAM!");
};
Supplier<String> supplierWithRecovery = SupplierUtils.recover(supplier, (ex) -> "Bla");
String result = supplierWithRecovery.get();
... |
@VisibleForTesting
WxMpService getWxMpService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMpService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MP.getType(), userType);
if (client != null && Objects.equals(client.getSta... | @Test
public void testGetWxMpService_clientEnable() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 数据
SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())
.setUserType(userType)... |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
final SchemaAndValue schemaAndValue = converter.toConnectData(topic, bytes);
final Object val = translator.toKsqlRow(schemaAndValue.schema(), schemaAndValue.value());
return SerdeUtils.castToTargetType(val, targetTy... | @Test
public void shouldDeserializeRecordsCorrectly() {
// When:
final String deserialized = connectDeserializer.deserialize(TOPIC, BYTES);
// Then:
verify(converter, times(1)).toConnectData(TOPIC, BYTES);
verify(dataTranslator, times(1)).toKsqlRow(schema, value);
assertThat(deserialized, is(... |
public void mix() {
LOGGER.info("Mixing the stew we find: {} potatoes, {} carrots, {} meat and {} peppers",
numPotatoes, numCarrots, numMeat, numPeppers);
} | @Test
void testMix() {
final var stew = new ImmutableStew(1, 2, 3, 4);
final var expectedMessage = "Mixing the immutable stew we find: 1 potatoes, "
+ "2 carrots, 3 meat and 4 peppers";
for (var i = 0; i < 20; i++) {
stew.mix();
assertEquals(expectedMessage, appender.getLastMessage())... |
@Nonnull
static String constructLookup(@Nonnull final String service, @Nonnull final String proto, @Nonnull final String name)
{
String lookup = "";
if ( !service.startsWith( "_" ) )
{
lookup += "_";
}
lookup += service;
if ( !lookup.endsWith( "." ) )... | @Test
public void testConstructLookup() throws Exception
{
// Setup test fixture.
final String service = "xmpp-client";
final String protocol = "tcp";
final String name = "igniterealtime.org";
// Execute system under test.
final String result = DNSUtil.constructL... |
@Override
public Iterable<ConnectorFactory> getConnectorFactories()
{
return ImmutableList.of(new RedisConnectorFactory(tableDescriptionSupplier));
} | @Test
public void testStartup()
{
RedisPlugin plugin = new RedisPlugin();
ConnectorFactory factory = getOnlyElement(plugin.getConnectorFactories());
assertInstanceOf(factory, RedisConnectorFactory.class);
Connector c = factory.create(
"test-connector",
... |
public Builder asBuilder() {
return new Builder(columns);
} | @Test
public void shouldDuplicateViaAsBuilder() {
// Given:
final Builder builder = SOME_SCHEMA.asBuilder();
// When:
final LogicalSchema clone = builder.build();
// Then:
assertThat(clone, is(SOME_SCHEMA));
} |
@CanIgnoreReturnValue
public <K1 extends K, V1 extends V> Caffeine<K1, V1> evictionListener(
RemovalListener<? super K1, ? super V1> evictionListener) {
requireState(this.evictionListener == null,
"eviction listener was already set to %s", this.evictionListener);
@SuppressWarnings("unchecked")
... | @Test
public void evictionListener() {
RemovalListener<Object, Object> removalListener = (k, v, c) -> {};
var builder = Caffeine.newBuilder().evictionListener(removalListener);
assertThat(builder.evictionListener).isSameInstanceAs(removalListener);
assertThat(builder.build()).isNotNull();
} |
public synchronized static MetricRegistry setDefault(String name) {
final MetricRegistry registry = getOrCreate(name);
return setDefault(name, registry);
} | @Test
public void errorsWhenDefaultAlreadySet() throws Exception {
try {
SharedMetricRegistries.setDefault("foobah");
SharedMetricRegistries.setDefault("borg");
} catch (final Exception e) {
assertThat(e).isInstanceOf(IllegalStateException.class);
asse... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertTextMessageContentNotStoredCreatesAmqpValueStringBody() throws Exception {
String contentString = "myTextMessageContent";
ActiveMQTextMessage outbound = createTextMessage(contentString);
outbound.onSend();
JMSMappingOutboundTransformer transformer = new ... |
public static MetricsMode fromString(String mode) {
if ("none".equalsIgnoreCase(mode)) {
return None.get();
} else if ("counts".equalsIgnoreCase(mode)) {
return Counts.get();
} else if ("full".equalsIgnoreCase(mode)) {
return Full.get();
}
Matcher truncateMatcher = TRUNCATE.matche... | @TestTemplate
public void testInvalidTruncationLength() {
assertThatThrownBy(() -> MetricsModes.fromString("truncate(0)"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Truncate length should be positive");
} |
public static byte[] decodeHex(String hexStr) {
return decodeHex((CharSequence) hexStr);
} | @Test
public void decodeHexTest(){
final String s = HexUtil.encodeHexStr("6");
final String s1 = HexUtil.decodeHexStr(s);
assertEquals("6", s1);
} |
@Override
public Map<String, Map<String, Double>> spellcheck(String indexName, String query, SpellcheckOptions options) {
return commandExecutor.get(spellcheckAsync(indexName, query, options));
} | @Test
public void testSpellcheck() {
RSearch s = redisson.getSearch();
s.createIndex("idx", IndexOptions.defaults()
.on(IndexType.HASH)
.prefix(Arrays.asList("doc:")),
FieldIndex.text("t1"),
FieldIndex.text("t2"));
... |
@Override
public IcebergEnumeratorState snapshotState(long checkpointId) {
return new IcebergEnumeratorState(
enumeratorPosition.get(), assigner.state(), enumerationHistory.snapshot());
} | @Test
public void testDiscoverWhenReaderRegistered() throws Exception {
TestingSplitEnumeratorContext<IcebergSourceSplit> enumeratorContext =
new TestingSplitEnumeratorContext<>(4);
ScanContext scanContext =
ScanContext.builder()
.streaming(true)
.startingStrategy(Strea... |
public Map<String, IndexMeta> getAllIndexes() {
return allIndexes;
} | @Test
public void testGetAllIndexes() {
Map<String, IndexMeta> allIndexes = tableMeta.getAllIndexes();
assertEquals(1, allIndexes.size(), "Should return all indexes added");
assertTrue(allIndexes.containsKey("primary"), "Should contain index 'primary'");
} |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetList1() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtils.get(Collections.emptyList(), -1);
});
} |
public void subscribeToEvent(
ResultPartitionID partitionId,
EventListener<TaskEvent> eventListener,
Class<? extends TaskEvent> eventType) {
checkNotNull(partitionId);
checkNotNull(eventListener);
checkNotNull(eventType);
TaskEventHandler taskEventHan... | @Test
void subscribeToEventNotRegistered() {
TaskEventDispatcher ted = new TaskEventDispatcher();
assertThatThrownBy(
() ->
ted.subscribeToEvent(
new ResultPartitionID(),
... |
public static String removeCharacter(String str, char charToRemove) {
if (str == null || str.indexOf(charToRemove) == -1) {
return str;
}
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != charToRemove) ... | @Test
void when_removingCharactersFromString_then_properValue() {
assertEquals("", StringUtil.removeCharacter("-------", '-'));
assertEquals("-------", StringUtil.removeCharacter("-------", '0'));
assertEquals("-------", StringUtil.removeCharacter("-0-0-0-0-0-0-", '0'));
assertEquals... |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
try {
return new DriveSearchListService(session, fileid, regex.toString()).list(workdir, listener);
}
catch(NotfoundExcepti... | @Test
public void testSearchFolder() throws Exception {
final String name = new AlphanumericRandomStringService().random();
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path workdir = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHomeFinderServi... |
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 testUnknownVersionFormat() {
assertThat(JavaVersion.parseMajorJavaVersion("Java9")).isEqualTo(6); // unknown format
} |
public void setRemoteIp(String remoteIp) {
this.remoteIp = remoteIp;
} | @Test
void testSetRemoteIp() {
assertNull(addressContext.getRemoteIp());
addressContext.setRemoteIp("127.0.0.1");
assertEquals("127.0.0.1", addressContext.getRemoteIp());
} |
@Override
public PageResult<JobLogDO> getJobLogPage(JobLogPageReqVO pageReqVO) {
return jobLogMapper.selectPage(pageReqVO);
} | @Test
public void testGetJobPage() {
// mock 数据
JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> {
o.setExecuteIndex(1);
o.setHandlerName("handlerName 单元测试");
o.setStatus(JobLogStatusEnum.SUCCESS.getStatus());
o.setBeginTime(buildTime(2021, 1, 8));
... |
public Class<?> getSerializedClass() {
return serializedClass;
} | @Test
void testConstructorWithCause() {
NacosSerializationException exception = new NacosSerializationException(new RuntimeException("test"));
assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals("errCode: 100, errMsg: Nacos serialize failed. ", excep... |
@Override
public Path createTempFile() throws IOException {
return createTempFile(null, null);
} | @Test
void shouldCreatedTempFile() throws IOException {
String workingDirId = IdUtils.create();
TestWorkingDir workingDirectory = new TestWorkingDir(workingDirId, new LocalWorkingDir(Path.of("/tmp/sub/dir/tmp/"), workingDirId));
Path tempFile = workingDirectory.createTempFile();
asse... |
public String compile(final String xls,
final String template,
int startRow,
int startCol) {
return compile( xls,
template,
InputType.XLS,
startRow,
... | @Test
public void testLoadBasicWithExtraCells() {
final String drl = converter.compile("/data/BasicWorkbook.drl.xls",
"/templates/test_template4.drl",
InputType.XLS,
10,
... |
@Override
public Collection<TaskExecutorPartitionInfo> getTrackedPartitionsFor(JobID producingJobId) {
return partitionTable.getTrackedPartitions(producingJobId).stream()
.map(
partitionId -> {
final PartitionInfo<JobID, TaskExecutorPartiti... | @Test
void testGetTrackedPartitionsFor() {
final TestingShuffleEnvironment testingShuffleEnvironment = new TestingShuffleEnvironment();
final JobID jobId = new JobID();
final ResultPartitionID resultPartitionId = new ResultPartitionID();
final TaskExecutorPartitionTracker partition... |
public void setLoggerLevel(LoggerRequest loggerRequest) throws BadRequestException {
try {
Class.forName(loggerRequest.getName());
} catch (Throwable ignore) {
throw new BadRequestException(
"The class of '" + loggerRequest.getName() + "' doesn't exists");
}
org.apache.log4j.Logge... | @Test
void testSetLoggerLevel() {
AdminService adminService = new AdminService();
String testLoggerName = "test";
org.apache.log4j.Logger logger = adminService.getLogger(testLoggerName);
org.apache.log4j.Level level = logger.getLevel();
boolean setInfo = false;
if (org.apache.log4j.Level.INFO ... |
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
if (response.status() == 404 || response.status() == 204)
if (JSONObject.class.isAssignableFrom((Class<?>) type))
return new JSONObject();
else if (JSONArray.class.isAssignableFrom((Class<?>) typ... | @Test
void decodesObject() throws IOException {
String json = "{\"a\":\"b\",\"c\":1}";
Response response = Response.builder()
.status(200)
.reason("OK")
.headers(Collections.emptyMap())
.body(json, UTF_8)
.request(request)
.build();
assertThat(jsonObject.sim... |
@Override
public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap,
String serviceInterface) {
if (!shouldHandle(invokers)) {
return invokers;
}
List<Object> targetInvokers;
if (routerConfig.isUseRequest... | @Test
public void testGetTargetInvokersByRequestWithMismatch() {
config.setUseRequestRouter(true);
config.setRequestTags(Arrays.asList("foo", "bar", "version"));
List<Object> invokers = new ArrayList<>();
ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0",
C... |
public static void setUserInfo(String username, String userRole) {
USER_THREAD_LOCAL.set(new User(username, userRole));
} | @Test
public void testSetUserInfo() {
UserContext.setUserInfo(USERNAME, USER_ROLE);
ThreadLocal<UserContext.User> userThreadLocal = (ThreadLocal<UserContext.User>) ReflectUtil.getFieldValue(UserContext.class, "USER_THREAD_LOCAL");
Assert.notNull(userThreadLocal.get());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.