focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static CodecFactory getCodecFactory(JobConf job) {
CodecFactory factory = null;
if (FileOutputFormat.getCompressOutput(job)) {
int deflateLevel = job.getInt(DEFLATE_LEVEL_KEY, DEFAULT_DEFLATE_LEVEL);
int xzLevel = job.getInt(XZ_LEVEL_KEY, DEFAULT_XZ_LEVEL);
int zstdLevel = job.getInt(ZSTD_LEV... | @Test
void deflateCodecUsingHadoopClass() {
CodecFactory avroDeflateCodec = CodecFactory.fromString("deflate");
JobConf job = new JobConf();
job.set("mapred.output.compress", "true");
job.set("mapred.output.compression.codec", "org.apache.hadoop.io.compress.DeflateCodec");
CodecFactory factory = ... |
@Override
public String toString() {
return "WebsocketConfig{"
+ "urls='"
+ urls
+ ", allowOrigin='"
+ allowOrigin
+ '}';
} | @Test
public void testToString() {
String toString = "WebsocketConfig{urls='%s, allowOrigin='%s}";
String expected = String.format(toString, URLS, ALLOW_ORIGIN);
assertEquals(expected, websocketConfig.toString());
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProviderInfo that = (ProviderInfo) o;
if (port != that.port) {
return false;
}
... | @Test
public void testEquals() throws Exception {
ProviderInfo p1 = new ProviderInfo();
ProviderInfo p2 = new ProviderInfo();
Assert.assertEquals(p1, p2);
List<ProviderInfo> ps = new ArrayList<ProviderInfo>();
ps.add(p1);
ps.remove(p2);
Assert.assertEquals(... |
public ContentInfo verify(ContentInfo signedMessage, Date date) {
final SignedData signedData = SignedData.getInstance(signedMessage.getContent());
final X509Certificate cert = certificate(signedData);
certificateVerifier.verify(cert, date);
final X500Name name = X500Name.getInstance(ce... | @Test
public void shouldThrowExceptionIfSerialNumberDoesNotMatch() throws Exception {
final byte[] data = fixture();
data[2118]++;
final ContentInfo signedMessage = ContentInfo.getInstance(data);
thrown.expect(VerificationException.class);
thrown.expectMessage("Serial number... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if(directory.isRoot()) {
final AttributedList<Path> list = new AttributedList<>();
for(RootFolder root : session.roots()) {
switch(root.g... | @Test
public void testList() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new Path("/My files", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path folder = new StoregateDirectoryFeature(session, nodeid).mkdir(new Path(r... |
private void setup() {
setLayout(new BorderLayout());
var bot = new JPanel();
add(jt.getTableHeader(), BorderLayout.NORTH);
bot.setLayout(new BorderLayout());
bot.add(del, BorderLayout.EAST);
add(bot, BorderLayout.SOUTH);
var jsp = new JScrollPane(jt);
jsp.setPreferredSize(new Dimension(... | @Test
void testSetup(){
final var target = new Target();
assertEquals(target.getSize().getWidth(), Double.valueOf(640));
assertEquals(target.getSize().getHeight(), Double.valueOf(480));
assertTrue(target.isVisible());
} |
public static int parseInteger(String str) {
return isNumber(str) ? Integer.parseInt(str) : 0;
} | @Test
void testParseInteger() throws Exception {
assertThat(StringUtils.parseInteger(null), equalTo(0));
assertThat(StringUtils.parseInteger("123"), equalTo(123));
} |
@Override
public MapperResult findConfigInfoAggrByPageFetchRows(MapperContext context) {
int startRow = context.getStartRow();
int pageSize = context.getPageSize();
String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID);
String groupId = (String) context.getWherePa... | @Test
void testFindConfigInfoAggrByPageFetchRows() {
String dataId = "data-id";
String groupId = "group-id";
String tenantId = "tenant-id";
Integer startRow = 0;
Integer pageSize = 5;
MapperContext context = new MapperContext();
context.putWhereParame... |
public QueryBuilders.QueryBuilder convert(Expr conjunct) {
return visit(conjunct);
} | @Test
public void testTranslateInPredicate() {
SlotRef codeSlotRef = mockSlotRef("code", Type.INT);
List<Expr> codeLiterals = new ArrayList<>();
IntLiteral codeLiteral1 = new IntLiteral(1);
IntLiteral codeLiteral2 = new IntLiteral(2);
IntLiteral codeLiteral3 = new IntLiteral(... |
void portAddedHelper(DeviceEvent event) {
log.debug("Instance port {} is detected from {}",
event.port().annotations().value(PORT_NAME),
event.subject().id());
// we check the existence of openstack port, in case VM creation
// event comes before port creation
... | @Test
public void testProcessPortAddedForUpdate() {
org.onosproject.net.Port addedPort = new DefaultPort(DEV1, P1, true, ANNOTATIONS);
DeviceEvent addedEvent = new DeviceEvent(DeviceEvent.Type.PORT_ADDED, DEV1, addedPort);
target.portAddedHelper(addedEvent);
//org.onosproject.net.P... |
public String getSource() {
return getFieldAs(String.class, FIELD_SOURCE);
} | @Test
public void testGetSource() throws Exception {
assertEquals("bar", message.getSource());
} |
public static boolean isEligibleForCarbonsDelivery(final Message stanza)
{
// To properly handle messages exchanged with a MUC (or similar service), the server must be able to identify MUC-related messages.
// This can be accomplished by tracking the clients' presence in MUCs, or by checking for the... | @Test
public void testNormalWithBodyPrivate() throws Exception
{
// Setup test fixture.
final Message input = new Message();
input.setType(Message.Type.normal);
input.setBody("This message is part of unit test " + getClass());
input.getElement().addElement("private", "urn... |
public ZContext()
{
this(1);
} | @Test(timeout = 5000)
public void testZContext()
{
ZContext ctx = new ZContext();
ctx.createSocket(SocketType.PAIR);
ctx.createSocket(SocketType.REQ);
ctx.createSocket(SocketType.REP);
ctx.createSocket(SocketType.PUB);
ctx.createSocket(SocketType.SUB);
ctx... |
public String expand(final String remote) {
return this.expand(remote, PREFIX);
} | @Test
public void testExpandPathWithDirectory() {
final String expanded = new TildePathExpander(new Path("/home/jenkins", EnumSet.of(Path.Type.directory)))
.expand("/~/f/s");
assertEquals("/home/jenkins/f/s", expanded);
} |
public static Future<Void> reconcileJmxSecret(Reconciliation reconciliation, SecretOperator secretOperator, SupportsJmx cluster) {
return secretOperator.getAsync(reconciliation.namespace(), cluster.jmx().secretName())
.compose(currentJmxSecret -> {
Secret desiredJmxSecret = ... | @Test
public void testEnabledJmxWithAuthWithMissingSecret(VertxTestContext context) {
KafkaClusterSpec spec = new KafkaClusterSpecBuilder()
.withNewJmxOptions()
.withNewKafkaJmxAuthenticationPassword()
.endKafkaJmxAuthenticationPassword()
... |
@Override
public SinkRecord newRecord(String topic, Integer kafkaPartition, Schema keySchema, Object key,
Schema valueSchema, Object value, Long timestamp,
Iterable<Header> headers) {
return new InternalSinkRecord(context, topic, kafkaPartition... | @Test
public void testNewRecordHeaders() {
SinkRecord sinkRecord = new SinkRecord(TOPIC, 0, null, null, null, null, 10);
ConsumerRecord<byte[], byte[]> consumerRecord = new ConsumerRecord<>("test-topic", 0, 10, null, null);
ProcessingContext<ConsumerRecord<byte[], byte[]>> context = new Proc... |
@Override
public boolean createReservation(ReservationId reservationId, String user,
Plan plan, ReservationDefinition contract) throws PlanningException {
LOG.info("placing the following ReservationRequest: " + contract);
try {
boolean res =
planner.createReservation(reservationId, use... | @Test
public void testAny() throws PlanningException {
prepareBasicPlan();
// create an ANY request, with an impossible step (last in list, first
// considered),
// and two satisfiable ones. We expect the second one to be returned.
ReservationDefinition rr = new ReservationDefinitionPBImpl();
... |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testMultipleCounterUpdates() throws IOException {
AppliedPTransform<?, ?, ?> myStep2 = mock(AppliedPTransform.class);
when(myStep2.getFullName()).thenReturn("myStepName");
BiMap<AppliedPTransform<?, ?, ?>, String> transformStepNames = HashBiMap.create();
transformStepNames.put(myStep... |
@Override
public PartitionQuickStats buildQuickStats(ConnectorSession session, SemiTransactionalHiveMetastore metastore,
SchemaTableName table, MetastoreContext metastoreContext, String partitionId, Iterator<HiveFileInfo> files)
{
requireNonNull(session);
requireNonNull(metastore);
... | @Test
public void testStatsAreBuiltFromFooters()
{
String resourceDir = TestParquetQuickStatsBuilder.class.getClassLoader().getResource("quick_stats").toString();
// Table : TPCDS SF 0.01 store_sales
ImmutableList<HiveFileInfo> hiveFileInfos = buildHiveFileInfos(resourceDir, "tpcds_sto... |
public String getLockMessage() throws KettleException {
return repObj.getLockMessage();
} | @Test
public void testGetLockMessage() throws Exception {
when( mockEERepositoryObject.getLockMessage() ).thenReturn( LOCK_MESSAGE );
assertEquals( LOCK_MESSAGE, uiTransformation.getLockMessage() );
} |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testCallSingleThatReturnsJson() {
run(
"def res = karate.callSingle('called3.js')"
);
matchVar("res", "{ varA: '2', varB: '3' }");
} |
@PostMapping("/authorize")
@Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@Parameters({
@Parameter(name = "response_type", required = true, description = "响应类型", example = "code"),
@Parameter(name = "client_id", required = true, descr... | @Test // autoApprove = false,但是不通过
public void testApproveOrDeny_ApproveNo() {
// 准备参数
String responseType = "token";
String clientId = randomString();
String scope = "{\"read\": true, \"write\": false}";
String redirectUri = "https://www.iocoder.cn";
String state = "... |
@Override
public List<GrokPattern> saveAll(Collection<GrokPattern> patterns, ImportStrategy importStrategy) throws ValidationException {
final Map<String, GrokPattern> newPatternsByName;
try {
newPatternsByName = patterns.stream().collect(Collectors.toMap(GrokPattern::name, Function.ide... | @Test
public void saveAllSucceedsWithValidGrokPatterns() throws ValidationException {
final List<GrokPattern> grokPatterns = Arrays.asList(
GrokPattern.create("NUMBER", "[0-9]+"),
GrokPattern.create("INT", "[+-]?%{NUMBER}"));
service.saveAll(grokPatterns, ABORT_ON_CON... |
@VisibleForTesting
public SmsChannelDO validateSmsChannel(Long channelId) {
SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId);
if (channelDO == null) {
throw exception(SMS_CHANNEL_NOT_EXISTS);
}
if (CommonStatusEnum.isDisable(channelDO.getStatus())) {
... | @Test
public void testValidateSmsChannel_notExists() {
// 准备参数
Long channelId = randomLongId();
// 调用,校验异常
assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId),
SMS_CHANNEL_NOT_EXISTS);
} |
public static Counter counter(MonitoringInfoMetricName metricName) {
return new DelegatingCounter(metricName);
} | @Test
public void testOperationsUpdateCounterFromContainerWhenContainerIsPresent() {
HashMap<String, String> labels = new HashMap<String, String>();
String urn = MonitoringInfoConstants.Urns.ELEMENT_COUNT;
MonitoringInfoMetricName name = MonitoringInfoMetricName.named(urn, labels);
MetricsContainer m... |
@Override
public <K, V> ICache<K, V> getCache(String name) {
checkNotNull(name, "Retrieving a cache instance with a null name is not allowed!");
return getCacheByFullName(HazelcastCacheManager.CACHE_MANAGER_PREFIX + name);
} | @Test
public void getCache_when_hazelcastExceptionIsThrown_then_isRethrown() {
// when a HazelcastException occurs whose cause is not a ServiceNotFoundException
HazelcastInstance hzInstance = mock(HazelcastInstance.class);
when(hzInstance.getDistributedObject(anyString(), anyString())).thenT... |
public JetSqlRow project(Object key, Object value) {
return project(key, null, value, null);
} | @Test
public void test_project() {
KvRowProjector projector = new KvRowProjector(
new QueryPath[]{QueryPath.KEY_PATH, QueryPath.VALUE_PATH},
new QueryDataType[]{INT, INT},
new IdentityTarget(),
new IdentityTarget(),
null,
... |
public GeometricDistribution(double p) {
if (p <= 0 || p > 1) {
throw new IllegalArgumentException("Invalid p: " + p);
}
this.p = p;
} | @Test
public void testGeometricDistribution() {
System.out.println("GeometricDistribution");
MathEx.setSeed(19650218); // to get repeatable results.
GeometricDistribution instance = new GeometricDistribution(0.4);
int[] data = instance.randi(1000);
GeometricDistribution est =... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testIllegalSpdyRstStreamFrameStreamId() throws Exception {
short type = 3;
byte flags = 0;
int length = 8;
int streamId = 0; // invalid stream identifier
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + leng... |
public List<SchemaChangeEvent> applySchemaChange(SchemaChangeEvent schemaChangeEvent) {
List<SchemaChangeEvent> events = new ArrayList<>();
TableId originalTable = schemaChangeEvent.tableId();
boolean noRouteMatched = true;
for (Tuple3<Selectors, String, String> route : routes) {
... | @Test
void testOneToOneMapping() {
SchemaDerivation schemaDerivation =
new SchemaDerivation(new SchemaManager(), ROUTES, new HashMap<>());
// Create table
List<SchemaChangeEvent> derivedChangesAfterCreateTable =
schemaDerivation.applySchemaChange(new CreateTa... |
@Override
public void checkCanSetCatalogSessionProperty(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String propertyName)
{
if (!canSetSessionProperty(identity, propertyName)) {
denySetSessionProperty(propertyName);
}
} | @Test
public void testSessionPropertyRules()
throws IOException
{
ConnectorAccessControl accessControl = createAccessControl("session_property.json");
accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("admin"), CONTEXT, "dangerous");
accessControl.check... |
public static KTableHolder<GenericKey> build(
final KGroupedStreamHolder groupedStream,
final StreamAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedStream,
aggregate,
buildContext,
... | @Test
public void shouldBuildUnwindowedAggregateWithCorrectSchema() {
// Given:
givenUnwindowedAggregate();
// When:
final KTableHolder<GenericKey> result = aggregate.build(planBuilder, planInfo);
// Then:
assertThat(result.getSchema(), is(OUTPUT_SCHEMA));
} |
public int compare(boolean b1, boolean b2) {
throw new UnsupportedOperationException(
"compare(boolean, boolean) was called on a non-boolean comparator: " + toString());
} | @Test
public void testBooleanComparator() {
Boolean[] valuesInAscendingOrder = {null, false, true};
for (int i = 0; i < valuesInAscendingOrder.length; ++i) {
for (int j = 0; j < valuesInAscendingOrder.length; ++j) {
Boolean vi = valuesInAscendingOrder[i];
Boolean vj = valuesInAscendingO... |
@Override
public void identify(String distinctId) {
} | @Test
public void identify() {
mSensorsAPI.identify("abcde");
Assert.assertNull(mSensorsAPI.getAnonymousId());
} |
public void setRetryContext(int maxRetries, int retryInterval,
long failuresValidityInterval) {
ContainerRetryContext retryContext = ContainerRetryContext
.newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null,
maxRetries, retryInterval, failuresValidityInterval);
containerLaunchC... | @Test
public void testContainerRetries() throws Exception {
DefaultProviderService providerService = new DefaultProviderService();
AbstractLauncher mockLauncher = mock(AbstractLauncher.class);
ContainerLaunchService.ComponentLaunchContext componentLaunchContext =
mock(ContainerLaunchService.Compo... |
public static <NodeT, EdgeT> List<List<NodeT>> allPathsFromRootsToLeaves(
Network<NodeT, EdgeT> network) {
ArrayDeque<List<NodeT>> paths = new ArrayDeque<>();
// Populate the list with all roots
for (NodeT node : network.nodes()) {
if (network.inDegree(node) == 0) {
paths.add(ImmutableLi... | @Test
public void testAllPathsFromRootsToLeaves() {
// Expected paths:
// D
// A, B, C, F
// A, B, E, G
// A, B, E, G (again)
// A, B, E, H
// I, J, E, G
// I, J, E, G (again)
// I, J, E, H
// I, E, G
// I, E, G (again)
// I, E, H
// I, K, L
// M, N, L
// M,... |
public double getX01FromLongitude(double longitude, boolean wrapEnabled) {
longitude = wrapEnabled ? Clip(longitude, getMinLongitude(), getMaxLongitude()) : longitude;
final double result = getX01FromLongitude(longitude);
return wrapEnabled ? Clip(result, 0, 1) : result;
} | @Test
public void testGetX01FromLongitude() {
final int iterations = 10;
for (int i = 0; i <= iterations; i++) {
final double longitude = tileSystem.getMinLongitude() + i * (tileSystem.getMaxLongitude() - tileSystem.getMinLongitude()) / iterations;
checkXY01(((double) i) / it... |
public void schedule(ExecutableMethod<?, ?> method) {
if (hasParametersOutsideOfJobContext(method.getTargetMethod())) {
throw new IllegalStateException("Methods annotated with " + Recurring.class.getName() + " can only have zero parameters or a single parameter of type JobContext.");
}
... | @Test
void beansWithMethodsAnnotatedWithRecurringCronAnnotationUsingJobContextWillAutomaticallyBeRegistered() {
final ExecutableMethod executableMethod = mock(ExecutableMethod.class);
final Method method = getRequiredMethod(MyServiceWithRecurringCronJobUsingJobContext.class, "myRecurringMethod", Job... |
public List<ContainerLogMeta> collect(
LogAggregationFileController fileController) throws IOException {
List<ContainerLogMeta> containersLogMeta = new ArrayList<>();
RemoteIterator<FileStatus> appDirs = fileController.
getApplicationDirectoriesOfUser(logsRequest.getUser());
while (appDirs.ha... | @Test
void testContainerIdExactMatch() throws IOException {
ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder request =
new ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder();
request.setAppId(null);
request.setContainerId(attemptContainer.toString());
request.setFileName(null);
req... |
public static <U, V> Pair<U, V> pair(U a, V b) {
return new Pair<>(a, b);
} | @Test
public void equalities(){
assertEquals(pair("a", "b"), pair("a", "b"));
assertNotEquals(pair("a", "b"), pair("a", "c"));
assertEquals(pair("a", pair("b", pair("c", null))), pair("a", pair("b", pair("c", null))));
} |
public Tuple2<Long, Long> cancel() throws Exception {
List<Tuple2<Future<? extends StateObject>, String>> pairs = new ArrayList<>();
pairs.add(new Tuple2<>(getKeyedStateManagedFuture(), "managed keyed"));
pairs.add(new Tuple2<>(getKeyedStateRawFuture(), "managed operator"));
pairs.add(ne... | @Test
void testCancelReturnsStateSize() throws Exception {
KeyGroupsStateHandle s1 =
new KeyGroupsStateHandle(
new KeyGroupRangeOffsets(0, 0),
new ByteStreamStateHandle("", new byte[123]));
KeyGroupsStateHandle s2 =
new ... |
public static Client connect(String url, ChannelHandler... handler) throws RemotingException {
return connect(URL.valueOf(url), handler);
} | @Test
void testConnect() throws RemotingException {
Assertions.assertThrows(RuntimeException.class, () -> Transporters.connect((String) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.connect((URL) null));
Assertions.assertNotNull(Transporters.connect(url));
... |
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
... | @Test
public void testHashpw() {
Assert.assertEquals(
"$2a$10$......................0li5vIK0lccG/IXHAOP2wBncDW/oa2u",
BCrypt.hashpw("foo", "$2a$10$......................"));
Assert.assertEquals(
"$2$09$......................GlnmyWmDnFB.MnSSUnFsiPvHsC2... |
@Override
protected String toHtmlDisplay(Element element, String query) {
String label = element.getLabel();
int index = label.toLowerCase().indexOf(query.toLowerCase());
String before = label.substring(0, index);
String match = label.substring(index, index + query.length());
... | @Test
public void testFirstOnly() {
Mockito.when(node.getLabel()).thenReturn("foobarfoo");
Assert.assertTrue(
new FuzzyElementLabelSearchProvider().toHtmlDisplay(node, "oo").contains("f<b>oo</b>barfoo"));
} |
public static void main(String[] args) {
Map<Integer, Instance> instanceMap = new HashMap<>();
var messageManager = new BullyMessageManager(instanceMap);
var instance1 = new BullyInstance(messageManager, 1, 1);
var instance2 = new BullyInstance(messageManager, 2, 1);
var instance3 = new BullyInsta... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> BullyApp.main(new String[]{}));
} |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesDate() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "string");
TextNode formatNode = TextNode.valueOf("date-time");
... |
public String documentationOf(String key) {
ConfigDef.ConfigKey configKey = definition.configKeys().get(key);
if (configKey == null)
return null;
return configKey.documentation;
} | @Test
public void testDocumentationOfExpectNull() {
Properties props = new Properties();
TestIndirectConfigResolution config = new TestIndirectConfigResolution(props);
assertNull(config.documentationOf("xyz"));
} |
@Override
public boolean isAutoUpdate() {
return packageDefinition.isAutoUpdate();
} | @Test
public void shouldDelegateToPackageDefinitionForAutoUpdate() throws Exception {
PackageDefinition packageDefinition = mock(PackageDefinition.class);
when(packageDefinition.isAutoUpdate()).thenReturn(false);
PackageMaterialConfig materialConfig = new PackageMaterialConfig(new CaseInsens... |
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(NAME_PREFIX + count.getAndIncrement());
t.setDaemon(true);
return t;
} | @Test
public void testName() {
GitThreadFactory factory = new GitThreadFactory();
assertThat(factory.newThread(() -> {
}).getName()).isEqualTo("git-scm-0");
assertThat(factory.newThread(() -> {
}).getName()).isEqualTo("git-scm-1");
} |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_submit_server_cli_version_minor_mismatch() {
String serverVersion = "5.0.0";
System.setProperty(HAZELCAST_INTERNAL_OVERRIDE_VERSION, serverVersion);
Config cfg = smallInstanceConfig();
cfg.getJetConfig().setResourceUploadEnabled(true);
String clusterNa... |
Map<String, String> unprocessedNodes(ConfigNode node) {
List<ConfigNode> nodes = new ArrayList<>();
findAllUnreadNodes(nodes, node);
return nodes.stream().map(this::process).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
} | @Test
public void shouldDetectUnappliedClientConfigEntries() {
Map<String, String> entries = new HashMap<>();
entries.put("HZCLIENT_FOO", "foo");
entries.put("HZCLIENT_NETWORK_SOCKETINTERCEPTOR_ENABLE", "true");
entries.put("HZCLIENT_NETWORK_SMARTROUTING", "true");
ConfigNod... |
public static int checkPattern( String text, String regexChar ) {
return checkPattern( text, regexChar, "" );
} | @Test
public void testCheckPattern() {
// Check more information in:
// https://docs.oracle.com/javase/tutorial/essential/regex/literals.html
String metacharacters = "<([{\\^-=$!|]})?*+.>";
for( int i = 0; i < metacharacters.length(); i++ ) {
int matches = TextFileInputUtils.checkPattern( metach... |
@Override
public Member next() {
Member memberToReturn = nextMember;
nextMember = null;
if (memberToReturn != null) {
return memberToReturn;
}
if (!advance()) {
throw new NoSuchElementException("no more elements");
}
memberToReturn = ne... | @Test(expected = NoSuchElementException.class)
public void give() {
int maxRetries = 0;
addClusterMember();
RestartingMemberIterator iterator = new RestartingMemberIterator(mockClusterService, maxRetries);
iterator.next();
//this should throw NoSuchElementException
... |
public boolean hasAvailableDiskSpace() {
return NameNodeResourcePolicy.areResourcesAvailable(volumes.values(),
minimumRedundantVolumes);
} | @Test
public void testCheckAvailability()
throws IOException {
conf.setLong(DFSConfigKeys.DFS_NAMENODE_DU_RESERVED_KEY, 0);
NameNodeResourceChecker nb = new NameNodeResourceChecker(conf);
assertTrue(
"isResourceAvailable must return true if " +
"disk usage is lower than threshold... |
public static boolean isEmail(CharSequence value) {
return isMatchRegex(EMAIL, value);
} | @Test
public void isEmailTest() {
final boolean email = Validator.isEmail("abc_cde@163.com");
assertTrue(email);
final boolean email1 = Validator.isEmail("abc_%cde@163.com");
assertTrue(email1);
final boolean email2 = Validator.isEmail("abc_%cde@aaa.c");
assertTrue(email2);
final boolean email3 = Validat... |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = RealtimeToOfflineSegmentsTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
String realtimeTableName = tableConfig.getTabl... | @Test
public void testTimeGap() {
Map<String, Map<String, String>> taskConfigsMap = new HashMap<>();
taskConfigsMap.put(RealtimeToOfflineSegmentsTask.TASK_TYPE, new HashMap<>());
TableConfig realtimeTableConfig = getRealtimeTableConfig(taskConfigsMap);
ClusterInfoAccessor mockClusterInfoProvide = moc... |
public static KeyFormat sanitizeKeyFormat(
final KeyFormat keyFormat,
final List<SqlType> newKeyColumnSqlTypes,
final boolean allowKeyFormatChangeToSupportNewKeySchema
) {
return sanitizeKeyFormatWrapping(
!allowKeyFormatChangeToSupportNewKeySchema ? keyFormat :
sanitizeKeyFormat... | @Test
public void shouldConvertKafkaFormatForSingleKeyWithUnsupportedPrimitiveType() {
// Given:
final KeyFormat format = KeyFormat.nonWindowed(
FormatInfo.of(KafkaFormat.NAME),
SerdeFeatures.of());
// When:
final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyFormat(format, Im... |
public void finish(StreamTaskActionExecutor actionExecutor, StopMode stopMode)
throws Exception {
if (!isHead && stopMode == StopMode.DRAIN) {
// NOTE: This only do for the case where the operator is one-input operator. At present,
// any non-head operator on the operator cha... | @Test
void testFinishingOperatorWithException() {
AbstractStreamOperator<Void> streamOperator =
new AbstractStreamOperator<Void>() {
@Override
public void finish() throws Exception {
throw new Exception("test exception at finish... |
@Override
protected void doStart() throws Exception {
super.doStart();
reconnect();
} | @Test
public void doStartTest() {
producer.start();
verify(connection).addIRCEventListener(listener);
verify(endpoint).joinChannels();
} |
@NotNull
public Map<OutputFile, String> getPathInfo() {
return pathInfo;
} | @Test
void pathInfoTest() {
ConfigBuilder configBuilder;
Map<OutputFile, String> pathInfo;
configBuilder = new ConfigBuilder(GeneratorBuilder.packageConfig(), DATA_SOURCE_CONFIG, GeneratorBuilder.strategyConfig(),
null, null, null);
pathInfo = configBuilder.getPathInfo();... |
@Nullable
public static Map<String, Set<FieldConfig.IndexType>> getSkipIndexes(Map<String, String> queryOptions) {
// Example config: skipIndexes='col1=inverted,range&col2=inverted'
String skipIndexesStr = queryOptions.get(QueryOptionKey.SKIP_INDEXES);
if (skipIndexesStr == null) {
return null;
... | @Test
public void testSkipIndexesParsing() {
String skipIndexesStr = "col1=inverted,range&col2=sorted";
Map<String, String> queryOptions =
Map.of(CommonConstants.Broker.Request.QueryOptionKey.SKIP_INDEXES, skipIndexesStr);
Map<String, Set<FieldConfig.IndexType>> skipIndexes = QueryOptionsUtils.get... |
@Override
@Transactional(rollbackFor = Exception.class)
public Long createCombinationActivity(CombinationActivityCreateReqVO createReqVO) {
// 校验商品 SPU 是否存在是否参加的别的活动
validateProductConflict(createReqVO.getSpuId(), null);
// 校验商品是否存在
validateProductExists(createReqVO.getSpuId(), c... | @Test
public void testCreateCombinationActivity_success() {
// 准备参数
CombinationActivityCreateReqVO reqVO = randomPojo(CombinationActivityCreateReqVO.class);
// 调用
Long combinationActivityId = combinationActivityService.createCombinationActivity(reqVO);
// 断言
assertNo... |
public static void validatePermission(@Nullable String tableName, AccessType accessType,
@Nullable HttpHeaders httpHeaders, String endpointUrl, AccessControl accessControl) {
String userMessage = getUserMessage(tableName, accessType, endpointUrl);
String rawTableName = TableNameBuilder.extractRawTableName... | @Test
public void testValidatePermissionWithNoSuchMethodError() {
AccessControl ac = Mockito.mock(AccessControl.class);
HttpHeaders mockHttpHeaders = Mockito.mock(HttpHeaders.class);
Mockito.when(ac.hasAccess(_table, AccessType.READ, mockHttpHeaders, _endpoint))
.thenThrow(new NoSuchMethodError("... |
@Override
public boolean test(final Path test) {
return this.equals(new DefaultPathPredicate(test));
} | @Test
public void testHashcodeCollision() {
assertNotEquals(
new DefaultPathPredicate(
new Path("19", EnumSet.of(Path.Type.file))
),
new DefaultPathPredicate(
new Path("0X", EnumSet.of(Path.Type.file))
... |
public Template getIndexTemplate(IndexSet indexSet) {
final IndexSetMappingTemplate indexSetMappingTemplate = getTemplateIndexSetConfig(indexSet, indexSet.getConfig(), profileService);
return indexMappingFactory.createIndexMapping(indexSet.getConfig())
.toTemplate(indexSetMappingTemplate... | @Test
void testUsesCustomMappingsWhileGettingTemplateWhenProfileIsNull() {
final CustomFieldMappings individualCustomFieldMappings = new CustomFieldMappings(List.of(
new CustomFieldMapping("f1", "string"),
new CustomFieldMapping("f2", "long")
));
final TestInd... |
public boolean skipFrame() throws IOException {
if (currentHeader != null) {
long toSkip = currentHeader.getLength() - HEADER_SIZE;
long skipped = IOUtils.skip(in, toSkip);
currentHeader = null;
if (skipped < toSkip) {
return false;
}
... | @Test
public void testSkipNoCurrentHeader() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write("This is a test".getBytes(UTF_8));
ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray());
stream = new MpegStream(in);
assertFal... |
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
final String param = exchange.getAttribute(Constants.PARAM_TRANSFORM);
ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);... | @Test
public void testDoExecuteParaIsBlankError() {
ServerWebExchange exchange = getServerWebExchange();
exchange.getAttributes().put(Constants.META_DATA, new MetaData());
RuleData data = mock(RuleData.class);
StepVerifier.create(grpcPlugin.doExecute(exchange, chain, selector, data))... |
@Override
public AppResponse process(Flow flow, ActivateWithCodeRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
Map<String, Object> result = digidClient.activateAccountWithCode(appSession.getAccountId(), request.getActivationCode());
if (result.get(lowerUnd... | @Test
public void responseBlockedTest() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
//given
when(digidClientMock.activateAccountWithCode(anyLong(), any())).thenReturn(Map.of(
lowerUnderscore(STATUS), "NOK",
lowerUnderscore(ERROR), "activation_code_... |
static Collection<Field> getAllFields(Class<?> owner, Predicate<? super Field> predicate) {
return getAll(owner, Class::getDeclaredFields).filter(predicate).collect(toList());
} | @Test
public void getAllFields_of_interface() {
assertThat(ReflectionUtils.getAllFields(Subinterface.class, alwaysTrue()))
.containsOnly(
field(SomeInterface.class, "SOME_CONSTANT"),
field(OtherInterface.class, "OTHER_CONSTANT"));
} |
Map<String, Object> parseForValidate(Map<String, String> props, Map<String, ConfigValue> configValues) {
Map<String, Object> parsed = new HashMap<>();
Set<String> configsWithNoParent = getConfigsWithNoParent();
for (String name: configsWithNoParent) {
parseForValidate(name, props, pa... | @Test
public void testParseForValidate() {
Map<String, Object> expectedParsed = new HashMap<>();
expectedParsed.put("a", 1);
expectedParsed.put("b", null);
expectedParsed.put("c", null);
expectedParsed.put("d", 10);
Map<String, ConfigValue> expected = new HashMap<>()... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
TbMsgMetaData metaDataCopy = msg.getMetaData().copy();
String data = msg.getData();
boolean msgChanged = false;
switch (renameIn) {
case METADATA:
... | @Test
void givenMsg_whenOnMsg_thenVerifyOutput() throws Exception {
String data = "{\"Temperature_1\":22.5,\"TestKey_2\":10.3}";
node.onMsg(ctx, getTbMsg(deviceId, data));
ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
verify(ctx, times(1)).tellSuccess(ne... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final Map<String, Object> event;
try {
event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT);
} catch (IOException e) {
... | @Test
public void decodeMessagesHandlesTopbeatMessages() throws Exception {
final Message message = codec.decode(messageFromJson("topbeat-system.json"));
assertThat(message).isNotNull();
assertThat(message.getSource()).isEqualTo("example.local");
assertThat(message.getTimestamp()).is... |
public Optional<DoFn.ProcessContinuation> run(
PartitionRecord partitionRecord,
ChangeStreamRecord record,
RestrictionTracker<StreamProgress, StreamProgress> tracker,
DoFn.OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
... | @Test
public void testHeartBeat() {
final Instant lowWatermark = Instant.ofEpochSecond(1000);
ChangeStreamContinuationToken changeStreamContinuationToken =
ChangeStreamContinuationToken.create(ByteStringRange.create("a", "b"), "1234");
Heartbeat mockHeartBeat = Mockito.mock(Heartbeat.class);
M... |
public static ServerId of(@Nullable String databaseId, String datasetId) {
if (databaseId != null) {
int databaseIdLength = databaseId.length();
checkArgument(databaseIdLength == DATABASE_ID_LENGTH, "Illegal databaseId length (%s)", databaseIdLength);
}
int datasetIdLength = datasetId.length();
... | @Test
@UseDataProvider("illegalDatabaseIdLengths")
public void of_throws_IAE_if_databaseId_length_is_not_8(int illegalDatabaseIdLengths) {
String databaseId = randomAlphabetic(illegalDatabaseIdLengths);
String datasetId = randomAlphabetic(UUID_DATASET_ID_LENGTH);
assertThatThrownBy(() -> ServerId.of(da... |
static int toInteger(final JsonNode object) {
if (object instanceof NumericNode) {
return object.intValue();
}
if (object instanceof TextNode) {
try {
return Integer.parseInt(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionException(... | @Test
public void shouldConvertStringToIntCorrectly() {
final Integer i = JsonSerdeUtils.toInteger(JsonNodeFactory.instance.textNode("1"));
assertThat(i, equalTo(1));
} |
public static void upgradeConfigurationAndVersion(RuleNode node, RuleNodeClassInfo nodeInfo) {
JsonNode oldConfiguration = node.getConfiguration();
int configurationVersion = node.getConfigurationVersion();
int currentVersion = nodeInfo.getCurrentVersion();
var configClass = nodeInfo.ge... | @Test
public void testUpgradeRuleNodeConfigurationWithNullConfig() throws Exception {
// GIVEN
var node = new RuleNode();
var nodeInfo = mock(RuleNodeClassInfo.class);
var nodeConfigClazz = TbGetAttributesNodeConfiguration.class;
var annotation = mock(org.thingsboard.rule.eng... |
public static UserOperatorConfig buildFromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(UserOperatorConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return new UserOperatorC... | @Test
public void testFromMapNamespaceEnvVarMissingThrows() {
Map<String, String> envVars = new HashMap<>(UserOperatorConfigTest.ENV_VARS);
envVars.remove(UserOperatorConfig.NAMESPACE.key());
assertThrows(InvalidConfigurationException.class, () -> UserOperatorConfig.buildFromMap(envVars));... |
public Result execute() {
long start = clock().getTick();
Result result;
try {
result = check();
} catch (Exception e) {
result = Result.unhealthy(e);
}
result.setDuration(TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECOND... | @Test
public void wrapsExceptionsWhenExecuted() {
final RuntimeException e = mock(RuntimeException.class);
when(e.getMessage()).thenReturn("oh noes");
when(underlying.execute()).thenThrow(e);
HealthCheck.Result actual = healthCheck.execute();
assertThat(actual.isHealthy())
... |
public String buildSql(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain)
{
// SELECT clause
StringBuilder sql = new StringBuilder("SELECT ");
if (columns.isEmpty()) {
sql.append("' '");
}
else {
String columnNames = columns.st... | @Test
public void testNotPushDoublePredicates()
{
List<HiveColumnHandle> columns = ImmutableList.of(
new HiveColumnHandle("quantity", HIVE_INT, parseTypeSignature(INTEGER), 0, REGULAR, Optional.empty(), Optional.empty()),
new HiveColumnHandle("extendedprice", HIVE_DOUBLE,... |
@Override
protected String buildHandle(final List<URIRegisterDTO> uriList, final SelectorDO selectorDO) {
List<GrpcUpstream> addList = buildGrpcUpstreamList(uriList);
List<GrpcUpstream> canAddList = new CopyOnWriteArrayList<>();
boolean isEventDeleted = uriList.size() == 1 && EventType.DELET... | @Test
public void testBuildHandle() {
shenyuClientRegisterGrpcService = spy(shenyuClientRegisterGrpcService);
final String returnStr = "[{upstreamUrl='localhost:8090',weight=1,status=true,timestamp=1637826588267},"
+ "{upstreamUrl='localhost:8091',weight=2,status=true,timestamp=1637... |
@Override
public FindCoordinatorRequest.Builder buildRequest(Set<CoordinatorKey> keys) {
unrepresentableKeys = keys.stream().filter(k -> k == null || !isRepresentableKey(k.idValue)).collect(Collectors.toSet());
Set<CoordinatorKey> representableKeys = keys.stream().filter(k -> k != null && isRepresen... | @Test
public void testBuildLookupRequest() {
CoordinatorStrategy strategy = new CoordinatorStrategy(CoordinatorType.GROUP, new LogContext());
FindCoordinatorRequest.Builder request = strategy.buildRequest(new HashSet<>(Arrays.asList(
CoordinatorKey.byGroupId("foo"),
Coordinat... |
public static String format(Object x) {
if (x != null) {
return format(x.toString());
} else {
return StrUtil.EMPTY;
}
} | @Test
public void testFormatLargeNumber() {
// 测试传入大数字的情况
String result = NumberWordFormatter.format(1234567890123L);
assertEquals("ONE TRILLION TWO HUNDRED AND THIRTY FOUR BILLION FIVE HUNDRED AND SIXTY SEVEN MILLION EIGHT HUNDRED AND NINETY THOUSAND ONE HUNDRED AND TWENTY THREE ONLY", result);
} |
public static String createGPX(InstructionList instructions, String trackName, long startTimeMillis, boolean includeElevation, boolean withRoute, boolean withTrack, boolean withWayPoints, String version, Translation tr) {
DateFormat formatter = Helper.createFormatter();
DecimalFormat decimalFormat = ne... | @Test
public void testCreateGPX() {
InstructionList instructions = new InstructionList(trMap.getWithFallBack(Locale.US));
PointList pl = new PointList();
pl.add(49.942576, 11.580384);
pl.add(49.941858, 11.582422);
instructions.add(new Instruction(Instruction.CONTINUE_ON_STREE... |
@Override
public final void run() {
long valueCount = collector.getMergingValueCount();
if (valueCount == 0) {
return;
}
runInternal();
assert operationCount > 0 : "No merge operations have been invoked in AbstractContainerMerger";
try {
lon... | @Test
@RequireAssertEnabled
public void testMergerRun_whenEmptyCollector_thenMergerDoesNotRun() {
TestMergeOperation operation = new TestMergeOperation();
TestContainerMerger merger = new TestContainerMerger(emptyCollector, nodeEngine, operation);
merger.run();
assertFalse("Exp... |
@Override
public ObjectNode encode(Alarm alarm, CodecContext context) {
checkNotNull(alarm, "Alarm cannot be null");
return context.mapper().createObjectNode()
.put("id", alarm.id().toString())
.put("deviceId", alarm.deviceId().toString())
.put("descr... | @Test
public void alarmCodecTestWithOptionalFieldMissing() {
JsonCodec<Alarm> codec = context.codec(Alarm.class);
assertThat(codec, is(notNullValue()));
ObjectNode alarmJson = codec.encode(alarmMinimumFields, context);
assertThat(alarmJson, notNullValue());
assertThat(alarmJ... |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void lifecycleDefault_shouldFailIfNotStarted() {
TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.create();
try {
testSource(resolveScopeFromLifecycle(lifecycle));
throw new AssertionError(
"Lifecycle resolution should have failed due to missing start " + "... |
@Override
public List<Intent> compile(LinkCollectionIntent intent, List<Intent> installable) {
SetMultimap<DeviceId, PortNumber> inputPorts = HashMultimap.create();
SetMultimap<DeviceId, PortNumber> outputPorts = HashMultimap.create();
Map<ConnectPoint, Identifier<?>> labels = ImmutableMap.... | @Test
public void singleHopTestForMp() {
Set<Link> testLinks = ImmutableSet.of();
Set<FilteredConnectPoint> ingress = ImmutableSet.of(
new FilteredConnectPoint(of1p1, vlan100Selector),
new FilteredConnectPoint(of1p2, vlan100Selector)
);
Set<FilteredC... |
@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 void putString(String key, String str) {
checkNotNull(key);
checkNotNull(str);
put(key, str);
} | @Test
void testArrayInvalidSingleValue() {
DescriptorProperties properties = new DescriptorProperties();
properties.putString(ARRAY_KEY, "INVALID");
assertThatThrownBy(() -> testArrayValidation(properties, 1, Integer.MAX_VALUE))
.isInstanceOf(ValidationException.class);
... |
@VisibleForTesting
static <T> Udaf<T, Struct, T> earliestT(
final boolean ignoreNulls
) {
return new Udaf<T, Struct, T>() {
Schema structSchema;
SqlType aggregateType;
SqlType returnType;
@Override
public void initializeTypeArguments(final List<SqlArgument> argTypeList) {
... | @Test
public void shouldInitialize() {
// Given:
final Udaf<Integer, Struct, Integer> udaf = EarliestByOffset
.earliestT(true);
// When:
final Struct init = udaf.initialize();
// Then:
assertThat(init, is(nullValue()));
} |
public void remove(long item1, long item2) {
lock.writeLock().lock();
try {
RoaringBitmap bitSet = map.get(item1);
if (bitSet != null) {
bitSet.remove(item2, item2 + 1);
if (bitSet.isEmpty()) {
map.remove(item1, bitSet);
... | @Test
public void testRemove() {
ConcurrentBitmapSortedLongPairSet set = new ConcurrentBitmapSortedLongPairSet();
int items = 10;
for (int i = 0; i < items; i++) {
set.add(1, i);
}
for (int i = 0; i < items / 2; i++) {
set.remove(1, i);
}
... |
@Override
public Map<K, V> getCachedMap() {
return localCacheView.getCachedMap();
} | @Test
public void testAddAndGet() {
RLocalCachedMap<Integer, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.<Integer, Integer>name("test")
.codec(new CompositeCodec(redisson.getConfig().getCodec(), IntegerCodec.INSTANCE)));
... |
@VisibleForTesting
static void initAddrUseFqdn(List<InetAddress> addrs) {
useFqdn = true;
analyzePriorityCidrs();
String fqdn = null;
if (PRIORITY_CIDRS.isEmpty()) {
// Get FQDN from local host by default.
try {
InetAddress localHost = InetAdd... | @Test(expected = IllegalAccessException.class)
public void testGetStartWithFQDNGetNullCanonicalHostName() {
testInitAddrUseFqdnCommonMock();
List<InetAddress> hosts = NetUtils.getHosts();
new MockUp<InetAddress>() {
@Mock
public InetAddress getLocalHost() throws Unkno... |
protected static String getPartition(String relative) {
return getParent(relative);
} | @Test
public void testGetPartition() {
assertEquals("year=2017/month=10",
getPartition("year=2017/month=10/part-0000.avro"));
} |
public void incBrokerPutNumsWithoutSystemTopic(final String topic, final int incValue) {
if (TopicValidator.isSystemTopic(topic)) {
return;
}
this.statsTable.get(BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC).getAndCreateStatsItem(this.clusterName).getValue().add(incValue);
} | @Test
public void testIncBrokerPutNumsWithoutSystemTopic() {
brokerStatsManager.incBrokerPutNumsWithoutSystemTopic(TOPIC, 1);
assertThat(brokerStatsManager.getStatsItem(BrokerStatsManager.BROKER_PUT_NUMS_WITHOUT_SYSTEM_TOPIC, CLUSTER_NAME)
.getValue().doubleValue()).isEqualTo(1L);
... |
@Override
public String toString() {
return "DataflowRunner#" + options.getJobName();
} | @Test
public void testToString() {
DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
options.setJobName("TestJobName");
options.setProject("test-project");
options.setRegion(REGION_ID);
options.setTempLocation("gs://test/temp/location");
options.setGcp... |
@NonNull
public List<FilePath> list() throws IOException, InterruptedException {
return list((FileFilter) null);
} | @Test public void listWithExcludes() throws Exception {
File baseDir = temp.getRoot();
final Set<FilePath> expected = new HashSet<>();
expected.add(createFilePath(baseDir, "top", "sub", "app.log"));
createFilePath(baseDir, "top", "sub", "trace.log");
expected.add(... |
@Override
public boolean match(Message msg, StreamRule rule) {
final boolean inverted = rule.getInverted();
final Object field = msg.getField(rule.getField());
if (field != null) {
final String value = field.toString();
return inverted ^ value.contains(rule.getValue(... | @Test
public void testSuccessfulMatchInArray() {
msg.addField("something", Collections.singleton("foobar"));
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(matcher.match(msg, rule));
} |
@SuppressWarnings( "unchecked" )
public List<? extends ConnectionDetails> getConnectionDetailsByScheme( String scheme ) {
initialize();
ConnectionProvider provider = connectionProviders.get( scheme );
if ( provider != null ) {
List<String> names = namesByConnectionProvider.get( provider.getName() );... | @Test
public void testGetConnectionDetailsBySchemeEmpty() {
addOne();
assertEquals( 0, connectionManager.getConnectionDetailsByScheme( DOES_NOT_EXIST ).size() );
} |
public static String getFullUrl(HttpServletRequest request) {
if (request.getQueryString() == null) {
return request.getRequestURI();
}
return request.getRequestURI() + "?" + request.getQueryString();
} | @Test
void formatsFullURIs() throws Exception {
assertThat(Servlets.getFullUrl(fullRequest))
.isEqualTo("/one/two?one=two&three=four");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.