focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@VisibleForTesting
void submitTrade(int slot, GrandExchangeOffer offer)
{
GrandExchangeOfferState state = offer.getState();
if (state != GrandExchangeOfferState.CANCELLED_BUY && state != GrandExchangeOfferState.CANCELLED_SELL && state != GrandExchangeOfferState.BUYING && state != GrandExchangeOfferState.SELLING)... | @Test
public void testDuplicateTrade()
{
SavedOffer savedOffer = new SavedOffer();
savedOffer.setItemId(ItemID.ABYSSAL_WHIP);
savedOffer.setQuantitySold(1);
savedOffer.setTotalQuantity(10);
savedOffer.setPrice(1000);
savedOffer.setSpent(25);
savedOffer.setState(GrandExchangeOfferState.BUYING);
when(co... |
public void setErrorValue(Object errorValue) {
this.errorValue = errorValue;
this.status = FactMappingValueStatus.FAILED_WITH_ERROR;
} | @Test
public void setErrorValue() {
value.setErrorValue(VALUE);
assertThat(value.getStatus()).isEqualTo(FactMappingValueStatus.FAILED_WITH_ERROR);
assertThat(value.getExceptionMessage()).isNull();
assertThat(value.getCollectionPathToValue()).isNull();
assertThat(valu... |
public TolerantIntegerComparison isWithin(int tolerance) {
return new TolerantIntegerComparison() {
@Override
public void of(int expected) {
Integer actual = IntegerSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, ... | @Test
public void isWithinOf() {
assertThat(20000).isWithin(0).of(20000);
assertThat(20000).isWithin(1).of(20000);
assertThat(20000).isWithin(10000).of(20000);
assertThat(20000).isWithin(10000).of(30000);
assertThat(Integer.MIN_VALUE).isWithin(1).of(Integer.MIN_VALUE + 1);
assertThat(Integer.M... |
@Override public Status status() {
return status;
} | @Test void status() {
assertThat(response.status()).isSameAs(status);
} |
@Override
public List<String> getFileLocations(String path) throws IOException {
List<String> ret = new ArrayList<>();
ret.add(NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, mUfsConf));
return ret;
} | @Test
public void getFileLocations() throws IOException {
byte[] bytes = getBytes();
String filepath = PathUtils.concatPath(mLocalUfsRoot, getUniqueFileName());
OutputStream os = mLocalUfs.create(filepath);
os.write(bytes);
os.close();
List<String> fileLocations = mLocalUfs.getFileLocations(... |
public void updateStatus(final String id, final String status) {
Optional<InstanceState> instanceState = InstanceState.get(status);
if (!instanceState.isPresent()) {
return;
}
if (instance.getMetaData().getId().equals(id)) {
instance.switchState(instanceState.get(... | @Test
void assertUpdateComputeNodeState() {
InstanceMetaData instanceMetaData = mock(InstanceMetaData.class);
when(instanceMetaData.getId()).thenReturn("foo_instance_id");
ComputeNodeInstanceContext context = new ComputeNodeInstanceContext(
new ComputeNodeInstance(instanceMet... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseCreateTypeStatement() {
// When:
List<CommandParser.ParsedCommand> commands = parse("create type address as struct<street varchar, number int, city string, zip varchar>;");
// Then:
assertThat(commands.size(), is(1));
assertThat(commands.get(0).getStatement().isPresen... |
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (methodClass != null) {
groups.add(methodClass);
}
Me... | @Test
void testItWithExistMethod() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod1", new Class<?>[] {String.clas... |
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
int posx = Arrays.bi... | @Test(expected = IllegalArgumentException.class)
public void disallowsQuantileOverOne() {
snapshot.getValue( 1.5 );
} |
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
DBSessions dbSes... | @Test
public void doFilter_disables_caching_in_DbSessions_even_if_chain_throws_exception() throws Exception {
RuntimeException thrown = mockChainDoFilterError();
try {
underTest.doFilter(request, response, chain);
fail("A RuntimeException should have been thrown");
} catch (RuntimeException e... |
@Override
public void deleteFileConfig(Long id) {
// 校验存在
FileConfigDO config = validateFileConfigExists(id);
if (Boolean.TRUE.equals(config.getMaster())) {
throw exception(FILE_CONFIG_DELETE_FAIL_MASTER);
}
// 删除
fileConfigMapper.deleteById(id);
... | @Test
public void testDeleteFileConfig_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> fileConfigService.deleteFileConfig(id), FILE_CONFIG_NOT_EXISTS);
} |
@Override
public Object[] getRowFromCache( RowMetaInterface lookupMeta, Object[] lookupRow ) throws KettleException {
if ( stepData.hasDBCondition ) {
// actually, there was no sense in executing SELECT from db in this case,
// should be reported as improvement
return null;
}
SearchingC... | @Test
public void lookup_Finds_FirstMatching() throws Exception {
ReadAllCache cache = buildCache( "=,IS NOT NULL,<=,IS NULL" );
Object[] found = cache.getRowFromCache( keysMeta.clone(), new Object[] { 1L, null, new Date( 1000000 ), null } );
assertArrayEquals( "(keys[0] == 1) && (keys[2] < 1000000) --> r... |
@Override
public int size() {
return size;
} | @Test
public void sizeIsInitiallyZero() {
assertEquals(0, set.size());
} |
@PostConstruct
public void init() {
// blockRequestHandlerOptional has low priority
blockRequestHandlerOptional.ifPresent(GatewayCallbackManager::setBlockHandler);
initAppType();
initFallback();
} | @Test
public void testInitWithFallbackRedirect() {
FallbackProperties fallbackProperties = mock(FallbackProperties.class);
when(gatewayProperties.getFallback()).thenReturn(fallbackProperties);
when(fallbackProperties.getMode()).thenReturn(ConfigConstants.FALLBACK_REDIRECT);
when(fallbackProperties.getRedirect(... |
@Override
@NonNull public Iterable<String> getNextWords(
@NonNull String currentWord, int maxResults, int minWordUsage) {
if (mNextNameParts.containsKey(currentWord)) {
return Arrays.asList(mNextNameParts.get(currentWord));
} else {
return Collections.emptyList();
}
} | @Test
public void testRegisterObserver() throws Exception {
ShadowContentResolver shadowContentResolver =
Shadows.shadowOf(getApplicationContext().getContentResolver());
final Collection<ContentObserver> contentObservers =
shadowContentResolver.getContentObservers(ContactsContract.Contacts.CON... |
public static boolean isAssignableFrom(Class clazz, Class cls) {
Objects.requireNonNull(cls, "cls");
return clazz.isAssignableFrom(cls);
} | @Test
void testIsAssignableFrom() {
assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class));
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
PointList pointList = way.getTag("point_list", null);
if (pointList != null) {
if (pointList.isEmpty() || !pointList.is3D()) {
if (maxSlopeEnc != null)
... | @Test
public void testAveragingOfMaxSlope() {
// point=49.977518%2C11.564285&point=49.979878%2C11.563663&profile=bike
DecimalEncodedValue averageEnc = AverageSlope.create();
DecimalEncodedValue maxEnc = MaxSlope.create();
new EncodingManager.Builder().add(averageEnc).add(maxEnc).buil... |
@Override
public void afterIntercept() {
if (!cancelled) {
try {
initIfNecessary();
} finally {
initCheckRT();
HealthCheckReactor.scheduleCheck(this);
}
}
} | @Test
void testAfterIntercept() {
healthCheckTaskV2.afterIntercept();
} |
@Override
public void createNetwork(Network osNet) {
checkNotNull(osNet, ERR_NULL_NETWORK);
checkArgument(!Strings.isNullOrEmpty(osNet.getId()), ERR_NULL_NETWORK_ID);
osNetworkStore.createNetwork(osNet);
OpenstackNetwork finalAugmentedNetwork = buildAugmentedNetworkFromType(osNet);... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateNetwork() {
target.createNetwork(NETWORK);
target.createNetwork(NETWORK);
} |
public void storeNewShortIds(
final ReportWorkItemStatusRequest request, final ReportWorkItemStatusResponse reply) {
checkArgument(
request.getWorkItemStatuses() != null
&& reply.getWorkItemServiceStates() != null
&& request.getWorkItemStatuses().size() == reply.getWorkItemServ... | @Test
public void testValidateNumberStatusesAndStates() {
CounterShortIdCache cache = new CounterShortIdCache();
ReportWorkItemStatusRequest request = new ReportWorkItemStatusRequest();
ReportWorkItemStatusResponse reply = new ReportWorkItemStatusResponse();
request.setWorkItemStatuses(
creat... |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowEncryptRulesStatement sqlStatement, final ContextManager contextManager) {
return rule.getConfiguration().getTables().stream().filter(each -> null == sqlStatement.getTableName() || each.getName().equalsIgnoreCase(sqlStatement.getTableNam... | @Test
void assertGetRowData() throws SQLException {
engine.executeQuery();
Collection<LocalDataQueryResultRow> actual = engine.getRows();
assertThat(actual.size(), is(1));
Iterator<LocalDataQueryResultRow> iterator = actual.iterator();
LocalDataQueryResultRow row = iterator.n... |
public static Stream<Vertex> reverseDepthFirst(Graph g) {
return reverseDepthFirst(g.getLeaves());
} | @Test
public void testReverseDFSVertex() {
DepthFirst.reverseDepthFirst(g.getLeaves()).forEach(v -> visitCount.incrementAndGet());
assertEquals("It should visit each node once", visitCount.get(), 3);
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testBraceletOfClayUsed()
{
when(configManager.getRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_CLAY, Integer.class)).thenReturn(25);
// Create equipment inventory with bracelet of clay
ItemContainer equipmentItemContainer = mock(ItemContainer.class);
when(cl... |
@POST
@Path("/token")
@Produces(MediaType.APPLICATION_JSON)
public Response token(
@FormParam("code") String code,
@FormParam("grant_type") String grantType,
@FormParam("redirect_uri") String redirectUri,
@FormParam("client_id") String clientId,
@FormParam("client_assertion_type") St... | @Test
void token() {
var tokenIssuer = mock(TokenIssuer.class);
var authenticator = mock(ClientAuthenticator.class);
var sut = new TokenEndpoint(tokenIssuer, authenticator);
var clientId = "myapp";
var grantType = "authorization_code";
var idToken = UUID.randomUUID().toString();
var a... |
@Override
public final void getSize(@NonNull SizeReadyCallback cb) {
sizeDeterminer.getSize(cb);
} | @Test
public void testSizeCallbackIsCalledSynchronouslyIfViewSizeSet() {
int dimens = 333;
// activity.get().setContentView(view);
view.layout(0, 0, dimens, dimens);
target.getSize(cb);
verify(cb).onSizeReady(eq(dimens), eq(dimens));
} |
@Override
public List<SnowflakeIdentifier> listSchemas(SnowflakeIdentifier scope) {
StringBuilder baseQuery = new StringBuilder("SHOW SCHEMAS");
String[] queryParams = null;
switch (scope.type()) {
case ROOT:
// account-level listing
baseQuery.append(" IN ACCOUNT");
break;
... | @SuppressWarnings("unchecked")
@Test
public void testListSchemasSQLExceptionAtRootLevel() throws SQLException, InterruptedException {
Exception injectedException =
new SQLException(String.format("SQL exception with Error Code %d", 0), "2000", 0, null);
when(mockClientPool.run(any(ClientPool.Action.c... |
@Override
public void accumulate(Object value) {
if (value == null) {
return;
}
if (this.value == null || compare(this.value, value) > 0) {
this.value = value;
}
} | @Test
public void test_serialization() {
MinSqlAggregation original = new MinSqlAggregation();
original.accumulate(1);
InternalSerializationService ss = new DefaultSerializationServiceBuilder().build();
MinSqlAggregation serialized = ss.toObject(ss.toData(original));
assert... |
public static ConnectSchema columnsToConnectSchema(final List<? extends SimpleColumn> columns) {
final SqlToConnectTypeConverter converter = SchemaConverters.sqlToConnectConverter();
final SchemaBuilder builder = SchemaBuilder.struct();
for (final SimpleColumn column : columns) {
final Schema colSche... | @Test
public void shouldConvertColumnsToStructSchema() {
// Given:
final LogicalSchema schema = LogicalSchema.builder()
.valueColumn(ColumnName.of("Vic"), DOUBLE)
.valueColumn(ColumnName.of("Bob"), BIGINT)
.build();
// When:
final ConnectSchema result = ConnectSchemas.columnsT... |
@Override
public String getStatementName(StatementContext statementContext) {
final ExtensionMethod extensionMethod = statementContext.getExtensionMethod();
if (extensionMethod == null) {
return null;
}
final Class<?> clazz = extensionMethod.getType();
final Time... | @Test
public void testNoAnnotations() throws Exception {
when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show")));
assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull();
} |
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("array(varchar(x))")
public static Block split(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice delimiter)
{
return split(string, delimiter, string.length() + 1);
} | @Test
public void testSplit()
{
assertFunction("SPLIT('a.b.c', '.')", new ArrayType(createVarcharType(5)), ImmutableList.of("a", "b", "c"));
assertFunction("SPLIT('ab', '.', 1)", new ArrayType(createVarcharType(2)), ImmutableList.of("ab"));
assertFunction("SPLIT('a.b', '.', 1)", new Arr... |
public void add(int value) {
add(Util.toUnsignedLong(value));
} | @Test
public void testBitmapValueAdd() {
// test add int
BitmapValue bitmapValue1 = new BitmapValue();
for (int i = 0; i < 10; i++) {
bitmapValue1.add(i);
}
checkBitmap(bitmapValue1, BitmapValue.SET_VALUE, 0, 10);
// test add long
BitmapValue bitm... |
@NonNull
public AuthorizationResponse auth(@NonNull AuthorizationRequest request) {
validateAuthorizationRequest(request);
var verifier = generatePkceCodeVerifier();
var codeChallenge = calculateS256CodeChallenge(verifier);
var relyingPartyCallback = baseUri.resolve("/auth/callback");
var ste... | @Test
void auth_badResponseType() {
var config = new RelyingPartyConfig(List.of("code"), List.of(REDIRECT_URI));
var sessionRepo = mock(SessionRepo.class);
var sut = new AuthService(BASE_URI, config, null, sessionRepo, null, null);
var scope = "openid";
var state = UUID.randomUUID().toString();
... |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
final Map<String, Object> headers = message.getHeaders();
CloudEvent cloudEvent = CloudEvents.v1_0;
headers.putIfAbsent(CloudEvents.CAMEL_CLOUD_EVENT_ID, message.getExchange().getExchangeId());
he... | @Test
void shouldMapToCloudEvent() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
exchange.getMessage().setHeader(Sqs2Constants.RECEIPT_HANDLE, "myQueue");
exchange.getMessage().setHeader(Sqs2Constants.MESSAGE_ID, "1234");
exchange.getMessage().setBody(new... |
public static Map<Node, Node> createNodes(Document document, String containerNodeName, String childNodeName, String nodeContent) {
return asStream(document.getElementsByTagName(containerNodeName))
.collect(Collectors.toMap(
containerNode -> containerNode,
... | @Test
public void createNodes() throws Exception {
final String newNodeName = "NEW_NODE_NAME";
final String newNodeValue = "NEW_NODE_VALUE";
Document document = DOMParserUtil.getDocument(XML);
Map<Node, Node> retrieved = DOMParserUtil.createNodes(document, MAIN_NODE, newNodeName, new... |
@Override
protected void doDelete(final List<RuleData> dataList) {
dataList.forEach(pluginDataSubscriber::unRuleSubscribe);
} | @Test
public void testDoDelete() {
List<RuleData> ruleDataList = createFakeRuleDateObjects(3);
ruleDataHandler.doDelete(ruleDataList);
ruleDataList.forEach(verify(subscriber)::unRuleSubscribe);
} |
@Override
public void remove(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName());
} | @Test
public void testRemove() {
Collection<RedisServer> masters = connection.masters();
connection.remove(masters.iterator().next());
} |
public static void addLiveSstFilesSizeMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
streamsMetrics,... | @Test
public void shouldAddLiveSstFilesSizeMetric() {
final String name = "live-sst-files-size";
final String description = "Total size in bytes of all SST files that belong to the latest LSM tree";
runAndVerifyMutableMetric(
name,
description,
() -> Rocks... |
public TurnServerOptions getRoutingFor(
@Nonnull final UUID aci,
@Nonnull final Optional<InetAddress> clientAddress,
final int instanceLimit
) {
try {
return getRoutingForInner(aci, clientAddress, instanceLimit);
} catch(Exception e) {
logger.error("Failed to perform routing", e)... | @Test
public void testRandomizes() throws UnknownHostException {
when(configTurnRouter.shouldRandomize())
.thenReturn(true);
assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10))
.isEqualTo(new TurnServerOptions(
TEST_HOSTNAME,
null... |
@Override
public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) {
ParamCheckResponse paramCheckResponse = new ParamCheckResponse();
if (paramInfos == null) {
paramCheckResponse.setSuccess(true);
return paramCheckResponse;
}
for (ParamInfo pa... | @Test
void testCheckParamInfoForCluster() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
// Max Length
String cluster = buildStringLength(65);
paramInfo.setCluster(cluster);
ParamCheckRe... |
@Override
@GetMapping("/presigned-url")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<?> getPresignedUrl(@Validated PresignedUrlDto.Req request, @AuthenticationPrincipal SecurityUserDetails user) {
return ResponseEntity.ok(storageUseCase.getPresignedUrl(user.getUserId(), request));
} | @Test
@WithSecurityMockUser
@DisplayName("Type이 CHAT이고, ChatroomId가 NULL일 때 400 응답을 반환한다.")
void getPresignedUrlWithNullChatroomId() throws Exception {
// given
PresignedUrlDto.Req request = new PresignedUrlDto.Req("CHAT", "jpg", null);
given(storageUseCase.getPresignedUrl(1L, reques... |
public StaticDirectory(List<Invoker<T>> invokers) {
this(null, invokers, null);
} | @Test
void testStaticDirectory() {
StateRouter router = new ConditionStateRouterFactory()
.getRouter(String.class, getRouteUrl(" => " + " host = " + NetUtils.getLocalHost()));
List<StateRouter> routers = new ArrayList<StateRouter>();
routers.add(router);
List<Invoker<... |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
@SuppressWarnings("ArraysAsListPrimitiveArray")
public void testCombiningAddBeforeRead() throws Exception {
GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR);
SettableFuture<Iterable<int[]>> future = SettableFuture.create();
when(mockReader.bagFuture(eq(COMBINING_... |
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.starts... | @Test
public void shouldReturnUnresolvedForOtherConfigIfNotStrict() {
assertThat(resolver.resolve("confluent.monitoring.interceptor.topic", false),
is(unresolvedItem("confluent.monitoring.interceptor.topic")));
} |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewName(), "New name must not be null!");
byte[] ... | @Test
public void testRename_keyNotExist() {
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot));
if (sameSlot) {
// This is a quirk of the implementation - since same-slot renames use the non... |
public Span nextSpan(Message message) {
TraceContextOrSamplingFlags extracted =
extractAndClearTraceIdProperties(processorExtractor, message, message);
Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler.
// When an upstream context was not present, lookup keys are unl... | @Test void nextSpan_should_use_span_from_headers_as_parent() {
setStringProperty(message, "b3", "0000000000000001-0000000000000002-1");
Span span = jmsTracing.nextSpan(message);
assertThat(span.context().parentId()).isEqualTo(2L);
} |
public static DistCpOptions parse(String[] args)
throws IllegalArgumentException {
CommandLineParser parser = new CustomParser();
CommandLine command;
try {
command = parser.parse(cliOptions, args, true);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to pars... | @Test
public void testParseUpdateRoot() {
DistCpOptions options = OptionsParser.parse(new String[] {
"hdfs://localhost:8020/source/first",
"hdfs://localhost:8020/target/"});
Assert.assertFalse(options.shouldUpdateRoot());
options = OptionsParser.parse(new String[] {
"-updateRoot",... |
@Override public Iterable<Result> buffer( Flowable<I> flowable ) {
Flowable<List<I>> buffer = millis > 0
? batchSize > 0 ? flowable.buffer( millis, MILLISECONDS, Schedulers.io(), batchSize, ArrayList::new, true )
: flowable.buffer( millis, MILLISECONDS )
: flowable.buffer( batchSize );
return ... | @Test
public void abortedSubtransThrowsAnError() throws KettleException {
Result result1 = new Result();
result1.setNrErrors( 1 );
when( subtransExecutor.execute( any() ) ).thenReturn( Optional.of( result1 ) );
when( subtransExecutor.getPrefetchCount() ).thenReturn( 10 );
RowMetaInterface rowMeta... |
public int getNameLength() {
return name_length;
} | @Test
public void testGetNameLength() {
assertEquals(TestParameters.nameLength, dle.getNameLength());
} |
@Override
public String key() {
return PropertyType.SINGLE_SELECT_LIST.name();
} | @Test
public void key() {
assertThat(validation.key()).isEqualTo("SINGLE_SELECT_LIST");
} |
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializerSnapshot<T> oldSerializerSnapshot) {
if (!(oldSerializerSnapshot instanceof PojoSerializerSnapshot)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
PojoSeria... | @Test
void testResolveSchemaCompatibilityWithCompatibleAfterMigrationFieldSerializers() {
final PojoSerializerSnapshot<TestPojo> oldSnapshot =
buildTestSnapshot(
Arrays.asList(
ID_FIELD,
NAME_FIELD,
... |
public static String prettyHex(byte[] data, int offset, int length) {
if (length == 0) return "";
final StringBuilder sb = new StringBuilder(length * 3 - 1);
sb.append(String.format("%02X", data[offset]));
for (int i = 1; i < length; i++) {
sb.append(String.format(" %02X", d... | @Test
public void prettyHexEmptyByteArray() {
assertEquals("", ByteArrayUtils.prettyHex(new byte[0]));
} |
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch,
Timer timer) {
metadata.addTransientTopics(topicsForPartitions(timestampsToSearch.keySet()));
try {
Map<TopicPartit... | @Test
public void testListOffsetsWithZeroTimeout() {
buildFetcher();
Map<TopicPartition, Long> offsetsToSearch = new HashMap<>();
offsetsToSearch.put(tp0, ListOffsetsRequest.EARLIEST_TIMESTAMP);
offsetsToSearch.put(tp1, ListOffsetsRequest.EARLIEST_TIMESTAMP);
Map<TopicParti... |
public static LinearModel fit(Formula formula, DataFrame data) {
return fit(formula, data, new Properties());
} | @Test
public void testCPU() {
System.out.println("CPU");
MathEx.setSeed(19650218); // to get repeatable results.
LinearModel model = RidgeRegression.fit(CPU.formula, CPU.data, 0.1);
System.out.println(model);
RegressionValidations<LinearModel> result = CrossValidation.regr... |
@Override
public ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos) {
String key = getServiceKey(request); // 每个方法级自己轮询,互不影响
int length = providerInfos.size(); // 总个数
PositiveAtomicCounter sequence = sequences.get(key);
if (sequence == null) {
se... | @Test
public void doSelect() throws Exception {
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(null);
Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
int size = 20;
int total = 190000;
SofaRequest request = new SofaRequest();
{
... |
@Config("router.config-file")
public RouterConfig setConfigFile(String configFile)
{
this.configFile = configFile;
return this;
} | @Test
public void testDefaults()
{
assertRecordedDefaults(recordDefaults(RouterConfig.class).setConfigFile(null));
} |
@Udf
public <T> Boolean contains(
@UdfParameter final String jsonArray,
@UdfParameter final T val
) {
try (JsonParser parser = PARSER_FACTORY.createParser(jsonArray)) {
if (parser.nextToken() != START_ARRAY) {
return false;
}
while (parser.nextToken() != null) {
fi... | @Test
public void shouldFindBooleansInJsonArray() {
assertEquals(true, jsonUdf.contains("[false, false, true, false]", true));
assertEquals(true, jsonUdf.contains("[true, true, false]", false));
assertEquals(false, jsonUdf.contains("[true, true]", false));
assertEquals(false, jsonUdf... |
void collectMetrics() {
MetricsPublisher[] publishersArr = publishers.toArray(new MetricsPublisher[0]);
PublisherMetricsCollector publisherCollector = new PublisherMetricsCollector(publishersArr);
collectMetrics(publisherCollector);
publisherCollector.publishCollectedMetrics();
} | @Test
public void testUpdatesRenderedInOrder() {
MetricsService metricsService = prepareMetricsService();
testProbeSource.update(1, 1.5D);
metricsService.collectMetrics(metricsCollectorMock);
testProbeSource.update(2, 5.5D);
metricsService.collectMetrics(metricsCollectorMoc... |
public static <T> Set<T> ofSet(T... values) {
int size = values == null ? 0 : values.length;
if (size < 1) {
return emptySet();
}
float loadFactor = 1f / ((size + 1) * 1.0f);
if (loadFactor > 0.75f) {
loadFactor = 0.75f;
}
Set<T> element... | @Test
void testOfSet() {
Set<String> set = ofSet();
assertEquals(emptySet(), set);
set = ofSet(((String[]) null));
assertEquals(emptySet(), set);
set = ofSet("A", "B", "C");
Set<String> expectedSet = new LinkedHashSet<>();
expectedSet.add("A");
expec... |
public static SingleInputSemanticProperties createProjectionPropertiesSingle(
int[] fields, CompositeType<?> inType) {
Character.isJavaIdentifierStart(1);
SingleInputSemanticProperties ssp = new SingleInputSemanticProperties();
int[] sourceOffsets = new int[inType.getArity()];
... | @Test
void testSingleProjectionProperties() {
int[] pMap = new int[] {3, 0, 4};
SingleInputSemanticProperties sp =
SemanticPropUtil.createProjectionPropertiesSingle(
pMap, (CompositeType<?>) fiveIntTupleType);
assertThat(sp.getForwardingTargetFields(0... |
@Override
public BlobDescriptor call() throws IOException, RegistryException {
EventHandlers eventHandlers = buildContext.getEventHandlers();
DescriptorDigest blobDigest = blobDescriptor.getDigest();
try (ProgressEventDispatcher progressEventDispatcher =
progressEventDispatcherFactory.create(
... | @Test
public void testCall_forcePushWithNoBlobCheck() throws IOException, RegistryException {
call(true);
Mockito.verify(registryClient, Mockito.never()).checkBlob(Mockito.any());
Mockito.verify(registryClient)
.pushBlob(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
} |
@Override
public Long computeValue(final Collection<T> elementsInBin, final int totalElements) {
return (long) elementsInBin.stream()
.mapToLong(valueRetrievalFunction)
.average()
.orElse(0L);
} | @Test
void testReturnsAverage() {
final Long result = toTest.computeValue(
List.of(
QueryExecutionStats.builder().duration(10).build(),
QueryExecutionStats.builder().duration(20).build(),
QueryExecutionStats.builder().du... |
public FEELFnResult<Object> invoke(@ParameterName("list") List list) {
if ( list == null || list.isEmpty() ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty"));
} else {
try {
return FEELFnResult.ofResult(C... | @Test
void invokeNullList() {
FunctionTestUtil.assertResultError(maxFunction.invoke((List) null), InvalidParametersEvent.class);
} |
Object[] findValues(int ordinal) {
return getAllValues(ordinal, type, 0);
} | @Test
public void testMapKeyReferenceToList() throws Exception {
ListType listType = new ListType();
listType.intValues = Arrays.asList(1, 2, 3);
Map<ListType, Integer> map = new HashMap<>();
map.put(listType, 1);
MapKeyReferenceAsList mapKeyReferenceAsList = new MapKeyRefe... |
public static MonthsWindows months(int number) {
return new MonthsWindows(number, 1, DEFAULT_START_DATE, DateTimeZone.UTC);
} | @Test
public void testDefaultWindowMappingFn() {
MonthsWindows windowFn = CalendarWindows.months(2);
WindowMappingFn<?> mapping = windowFn.getDefaultWindowMappingFn();
assertThat(
mapping.getSideInputWindow(
new BoundedWindow() {
@Override
public Instant ma... |
@Override
public int compare(String version1, String version2) {
if(ObjectUtil.equal(version1, version2)) {
return 0;
}
if (version1 == null && version2 == null) {
return 0;
} else if (version1 == null) {// null或""视为最小版本,排在前
return -1;
} else if (version2 == null) {
return 1;
}
return Compar... | @Test
public void I8Z3VETest() {
// 传递性测试
int compare = VersionComparator.INSTANCE.compare("260", "a-34");
assertTrue(compare > 0);
compare = VersionComparator.INSTANCE.compare("a-34", "a-3");
assertTrue(compare > 0);
compare = VersionComparator.INSTANCE.compare("260", "a-3");
assertTrue(compare > 0);
} |
public void receiveMessage(ProxyContext ctx, ReceiveMessageRequest request,
StreamObserver<ReceiveMessageResponse> responseObserver) {
ReceiveMessageResponseStreamWriter writer = createWriter(ctx, responseObserver);
try {
Settings settings = this.grpcClientSettingsManager.getClientS... | @Test
public void testReceiveMessage() {
StreamObserver<ReceiveMessageResponse> receiveStreamObserver = mock(ServerCallStreamObserver.class);
ArgumentCaptor<ReceiveMessageResponse> responseArgumentCaptor = ArgumentCaptor.forClass(ReceiveMessageResponse.class);
doNothing().when(receiveStreamO... |
@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 AcGroupAccessControlWrong() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaimsGroup("stevehu", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("account.r", "account.w"), "backOffice");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String... |
public List<Stream> getStreams() {
return streams;
} | @Test
public void testGetStreams() throws Exception {
final StreamMock stream = getStreamMock("test");
final StreamRouterEngine engine = newEngine(Lists.newArrayList(stream));
assertEquals(Lists.newArrayList(stream), engine.getStreams());
} |
public static int parseHexToInt(String hex) {
return parseHexToInt(hex, true);
} | @Test
public void parseHexToInt() {
Assertions.assertEquals(0xAB, TbUtils.parseHexToInt("AB"));
Assertions.assertEquals(0xABBA, TbUtils.parseHexToInt("ABBA", true));
Assertions.assertEquals(0xBAAB, TbUtils.parseHexToInt("ABBA", false));
Assertions.assertEquals(0xAABBCC, TbUtils.pars... |
public static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName) {
if (values == null) {
// pass
return;
}
for (String value : values) {
Preconditions.checkNotNull(
value, "Property '" + propertyName + "' cannot contain null en... | @Test
public void testCheckNullOrNonNullNonEmptyEntries_mapNullKeyFail() {
try {
Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap(null, "val1"), "test");
Assert.fail();
} catch (NullPointerException npe) {
Assert.assertEquals("Property 'test' cannot contain null keys", np... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertFloat() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("float")
.dataType("float")
.build();
Column column = Oracle... |
Map<String, Object> targetAdminConfig(String role) {
Map<String, Object> props = new HashMap<>();
props.putAll(originalsWithPrefix(TARGET_CLUSTER_PREFIX));
props.keySet().retainAll(MirrorClientConfig.CLIENT_CONFIG_DEF.names());
props.putAll(originalsWithPrefix(ADMIN_CLIENT_PREFIX));
... | @Test
public void testTargetAdminConfig() {
Map<String, String> connectorProps = makeProps(
MirrorConnectorConfig.ADMIN_CLIENT_PREFIX +
"connections.max.idle.ms", "10000"
);
MirrorConnectorConfig config = new TestMirrorConnectorConfig(connectorProps);
... |
static Time toTime(final JsonNode object) {
if (object instanceof NumericNode) {
return returnTimeOrThrow(object.asLong());
}
if (object instanceof TextNode) {
try {
return returnTimeOrThrow(Long.parseLong(object.textValue()));
} catch (final NumberFormatException e) {
thro... | @Test
public void shouldNotConvertNegativeNumberToTime() {
try {
JsonSerdeUtils.toTime(JsonNodeFactory.instance.numberNode(-5));
} catch (Exception e) {
assertThat(e.getMessage(), equalTo("Time values must use number of milliseconds greater than 0 and less than 86400000."));
}
} |
public static FindKV findKV(String regex, int keyGroup, int valueGroup) {
return findKV(Pattern.compile(regex), keyGroup, valueGroup);
} | @Test
@Category(NeedsRunner.class)
public void testKVFindName() {
PCollection<KV<String, String>> output =
p.apply(Create.of("a b c"))
.apply(Regex.findKV("a (?<keyname>b) (?<valuename>c)", "keyname", "valuename"));
PAssert.that(output).containsInAnyOrder(KV.of("b", "c"));
p.run();... |
public File getJvmOptions() {
return new File(confDirectory, "jvm.options");
} | @Test
public void getJvmOptions_is_in_es_conf_directory() throws IOException {
File tempDir = temp.newFolder();
Props props = new Props(new Properties());
props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath());
props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath());
props.set... |
public long position()
{
if (isClosed)
{
return finalPosition;
}
return subscriberPosition.get();
} | @Test
void shouldAllowValidPosition()
{
final Image image = createImage();
final long expectedPosition = TERM_BUFFER_LENGTH - 32;
position.setOrdered(expectedPosition);
assertThat(image.position(), is(expectedPosition));
image.position(TERM_BUFFER_LENGTH);
asser... |
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException {
if (StringUtils.isBlank(filter)) {
return true;
}
Script script;
try {
script = ENGINE.createScript(filter);
} catch (JexlException e) {
throw new FeedEntryFilterException("Exception while parsing exp... | @Test
void cannotLoopForever() {
Mockito.when(config.feedRefresh().filteringExpressionEvaluationTimeout()).thenReturn(Duration.ofMillis(200));
service = new FeedEntryFilteringService(config);
Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("while(true) {}", entry));
} |
@Override
@SneakyThrows
public WxJsapiSignature createWxMpJsapiSignature(Integer userType, String url) {
WxMpService service = getWxMpService(userType);
return service.createJsapiSignature(url);
} | @Test
public void testCreateWxMpJsapiSignature() throws WxErrorException {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
String url = randomString();
// mock 方法
WxJsapiSignature signature = randomPojo(WxJsapiSignature.class);
when(wxMpService.c... |
@SuppressWarnings({"unchecked", "rawtypes"})
public Collection<DataNode> getDataNodes(final String tableName) {
Collection<DataNode> result = getDataNodesByTableName(tableName);
if (result.isEmpty()) {
return result;
}
for (Entry<ShardingSphereRule, DataNodeBuilder> entry... | @Test
void assertGetDataNodesForSingleTableWithDataNodeContainedRuleWithoutDataSourceContainedRule() {
DataNodes dataNodes = new DataNodes(mockDataNodeRules());
Collection<DataNode> actual = dataNodes.getDataNodes("t_single");
assertThat(actual.size(), is(1));
Iterator<DataNode> iter... |
@Override
public String getOnuStatistics(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId(... | @Test
public void testValidGetOnuStats() throws Exception {
String reply;
String target;
for (int i = ZERO; i < VALID_GET_STATS_TCS.length; i++) {
target = VALID_GET_STATS_TCS[i];
currentKey = i;
reply = voltConfig.getOnuStatistics(target);
as... |
@Override
public long getPeriodMillis() {
return periodMillis;
} | @Test
public void testGetPeriodMillis() {
assertEquals(1000, plugin.getPeriodMillis());
} |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
TikaInputStream tis = TikaInputStream.get(stream, new TemporaryResources(), metadata);
File tmpFile = tis.getFile();
Gro... | @Test
public void testJournalParser() {
String path = "/test-documents/testJournalParser.pdf";
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
assumeTrue(canRun());
InputStream stream = JournalParserTest.class.getResourceAsStream(path)... |
static void handleDowngrade(Namespace namespace, Admin adminClient) throws TerseException {
handleUpgradeOrDowngrade("downgrade", namespace, adminClient, downgradeType(namespace));
} | @Test
public void testHandleDowngradeDryRun() {
Map<String, Object> namespace = new HashMap<>();
namespace.put("metadata", "3.3-IV3");
namespace.put("feature", Collections.singletonList("foo.bar=1"));
namespace.put("dry_run", true);
String downgradeOutput = ToolsTestUtils.cap... |
public static File applyBaseDirIfRelative(File baseDir, File actualFileToUse) {
if (actualFileToUse == null) {
return baseDir;
}
if (actualFileToUse.isAbsolute()) {
return actualFileToUse;
}
if (StringUtils.isBlank(baseDir.getPath())) {
return... | @Test
void shouldUseDefaultIfActualIsNull() {
final File baseFile = new File("xyz");
assertThat(FileUtil.applyBaseDirIfRelative(baseFile, null)).isEqualTo(baseFile);
} |
public List<String> listOfConfigKeys() {
ArrayList<String> list = new ArrayList<>();
for (ConfigurationProperty configurationProperty : this) {
list.add(configurationProperty.getConfigurationKey().getName());
}
return list;
} | @Test
void shouldGetConfigurationKeysAsList() {
ConfigurationProperty property1 = new ConfigurationProperty(new ConfigurationKey("key1"), new ConfigurationValue("value1"), null, null);
ConfigurationProperty property2 = new ConfigurationProperty(new ConfigurationKey("key2"), new ConfigurationValue("v... |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
// 默认使用积分为 0
result.setUsePoint(0);
// 1.1 校验是否使用积分
if (!BooleanUtil.isTrue(param.getPointStatus())) {
result.setUsePoint(0);
return;
}
// 1.2 校... | @Test
public void testCalculate_TradeDeductMaxPrice() {
// 准备参数
TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
.setUserId(233L).setPointStatus(true) // 是否使用积分
.setItems(asList(
new TradePriceCalculateReqBO.Item().setSkuId(10L).... |
@Override
public Mono<User> updatePassword(String username, String newPassword) {
return getUser(username)
.filter(user -> !Objects.equals(user.getSpec().getPassword(), newPassword))
.flatMap(user -> {
user.getSpec().setPassword(newPassword);
return cl... | @Test
void shouldUpdatePasswordIfUserFoundInExtension() {
var fakeUser = new User();
fakeUser.setSpec(new User.UserSpec());
when(client.get(User.class, "faker")).thenReturn(Mono.just(fakeUser));
when(client.update(eq(fakeUser))).thenReturn(Mono.just(fakeUser));
StepVerifier... |
@Override
public boolean deleteAll(JobID jobId) {
return delete(BlobUtils.getStorageLocationPath(basePath, jobId));
} | @Test
void testDeleteAllWithNotExistingJobId() {
final JobID jobId = new JobID();
assertThat(testInstance.deleteAll(jobId)).isTrue();
assertThat(getPath(jobId)).doesNotExist();
} |
public Editor edit(String key) throws IOException {
return edit(key, ANY_SEQUENCE_NUMBER);
} | @Test public void cannotOperateOnEditAfterRevert() throws Exception {
DiskLruCache.Editor editor = cache.edit("k1");
editor.set(0, "A");
editor.set(1, "B");
editor.abort();
assertInoperable(editor);
} |
public static <T extends PipelineOptions> T validateCli(Class<T> klass, PipelineOptions options) {
return validate(klass, options, true);
} | @Test
public void testValidationOnOverriddenMethodsCli() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"Missing required value for " + "[--object, \"Fake Description\"].");
SubClassValidation required =
PipelineOptionsFactory... |
public void poll(final long timeoutMs, final long currentTimeMs) {
trySend(currentTimeMs);
long pollTimeoutMs = timeoutMs;
if (!unsentRequests.isEmpty()) {
pollTimeoutMs = Math.min(retryBackoffMs, pollTimeoutMs);
}
this.client.poll(pollTimeoutMs, currentTimeMs);
... | @Test
public void testPropagateMetadataError() {
AuthenticationException authException = new AuthenticationException("Test Auth Exception");
doThrow(authException).when(metadata).maybeThrowAnyException();
LinkedList<BackgroundEvent> backgroundEventQueue = new LinkedList<>();
this.ba... |
public void setEphemeral(boolean ephemeral) {
this.ephemeral = ephemeral;
} | @Test
void testSetEphemeral() {
serviceMetadata.setEphemeral(false);
assertFalse(serviceMetadata.isEphemeral());
} |
public static ClusterHealthStatus isHealth(List<RemoteInstance> remoteInstances) {
if (CollectionUtils.isEmpty(remoteInstances)) {
return ClusterHealthStatus.unHealth("can't get the instance list");
}
if (!CoreModuleConfig.Role.Receiver.equals(ROLE)) {
List<RemoteInstance... | @Test
public void unHealthWithEmptyInstance() {
ClusterHealthStatus clusterHealthStatus = OAPNodeChecker.isHealth(Lists.newArrayList());
Assertions.assertFalse(clusterHealthStatus.isHealth());
} |
@Nullable
public DnsCache resolveCache() {
return resolveCache;
} | @Test
void resolveCacheBadValues() {
assertThat(builder.build().resolveCache()).isNull();
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> builder.resolveCache(null));
} |
public static void createTopics(
Logger log, String bootstrapServers, Map<String, String> commonClientConf,
Map<String, String> adminClientConf,
Map<String, NewTopic> topics, boolean failOnExisting) throws Throwable {
// this method wraps the call to createTopics() that takes admin clien... | @Test
public void testCreatesOneTopicVerifiesOneTopic() throws Throwable {
final String existingTopic = "existing-topic";
List<TopicPartitionInfo> tpInfo = new ArrayList<>();
tpInfo.add(new TopicPartitionInfo(0, broker1, singleReplica, Collections.emptyList()));
tpInfo.add(new TopicP... |
public void resumePollingForPartitionsWithAvailableSpace() {
for (final Task t: tasks.activeTasks()) {
t.resumePollingForPartitionsWithAvailableSpace();
}
} | @Test
public void shouldResumePollingForPartitionsWithAvailableSpaceForAllActiveTasks() {
final StreamTask activeTask1 = statefulTask(taskId00, taskId00ChangelogPartitions)
.inState(State.RUNNING)
.withInputPartitions(taskId00Partitions).build();
final StreamTask activeTask2 ... |
public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) {
if (chunked) {
m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
m.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
} else {
List<String> encodings = m.headers... | @Test
public void testDoubleChunkedHeader() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().add(HttpHeaderNames.TRANSFER_ENCODING, "chunked");
HttpUtil.setTransferEncodingChunked(message, true);
List<String> expected = s... |
static SelType callJavaMethod(Object javaObj, SelType[] args, MethodHandle m, String methodName) {
try {
if (args.length == 0) {
return callJavaMethod0(javaObj, m);
} else if (args.length == 1) {
return callJavaMethod1(javaObj, args[0], m);
} else if (args.length == 2) {
re... | @Test
public void testCallJavaMethodWithTwoArgs() throws Throwable {
m1 =
MethodHandles.lookup()
.findStatic(
MockType.class,
"staticTwoArgs",
MethodType.methodType(double.class, double.class, boolean.class));
m2 =
MethodHandles.looku... |
public static List<ReservationAllocationState>
convertAllocationsToReservationInfo(Set<ReservationAllocation> res,
boolean includeResourceAllocations) {
List<ReservationAllocationState> reservationInfo = new ArrayList<>();
Map<ReservationInterval, Resource> requests;
for (Re... | @Test
public void testConvertAllocationsToReservationInfoEmptySet() {
List<ReservationAllocationState> infoList = ReservationSystemUtil
.convertAllocationsToReservationInfo(
Collections.<ReservationAllocation>emptySet(), false);
assertThat(infoList).isEmpty();
} |
public static void validateGroupInstanceId(String id) {
Topic.validate(id, "Group instance id", message -> {
throw new InvalidConfigurationException(message);
});
} | @Test
public void shouldThrowOnInvalidGroupInstanceIds() {
char[] longString = new char[250];
Arrays.fill(longString, 'a');
String[] invalidGroupInstanceIds = {"", "foo bar", "..", "foo:bar", "foo=bar", ".", new String(longString)};
for (String instanceId : invalidGroupInstanceIds) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.