下面列出了怎么用org.testng.collections.Lists的API类实例代码及写法,或者点击链接到github查看源代码。
public List<ITestNGMethod> getMethodsThatBelongTo(String group, ITestNGMethod fromMethod) {
Set<String> uniqueKeys = m_groups.keySet();
List<ITestNGMethod> result = Lists.newArrayList();
for (String k : uniqueKeys) {
if (Pattern.matches(group, k)) {
result.addAll(m_groups.get(k));
}
}
if (result.isEmpty() && !fromMethod.ignoreMissingDependencies()) {
throw new TestNGException("DependencyMap::Method \"" + fromMethod
+ "\" depends on nonexistent group \"" + group + "\"");
} else {
return result;
}
}
/**
* Create the test methods that belong to this class (rejects
* all those that belong to a different class).
*/
private ITestNGMethod[] createTestMethods(ITestNGMethod[] methods) {
List<ITestNGMethod> vResult = Lists.newArrayList();
for (ITestNGMethod tm : methods) {
ConstructorOrMethod m = tm.getConstructorOrMethod();
if (m.getDeclaringClass().isAssignableFrom(m_testClass)) {
for (Object o : m_iClass.getInstances(false)) {
log(4, "Adding method " + tm + " on TestClass " + m_testClass);
vResult.add(new TestNGScenario(/* tm.getRealClass(), */ m.getMethod(), m_annotationFinder, m_xmlTest,
o));
}
}
else {
log(4, "Rejecting method " + tm + " for TestClass " + m_testClass);
}
}
ITestNGMethod[] result = vResult.toArray(new ITestNGMethod[vResult.size()]);
return result;
}
/**
* Apply the method interceptor (if applicable) to the list of methods.
*/
private ITestNGMethod[] intercept(ITestNGMethod[] methods) {
List<IMethodInstance> methodInstances = methodsToMethodInstances(Arrays.asList(methods));
// add built-in interceptor (PreserveOrderMethodInterceptor or InstanceOrderingMethodInterceptor at the end of the list
m_methodInterceptors.add(builtinInterceptor);
for (IMethodInterceptor m_methodInterceptor : m_methodInterceptors) {
methodInstances = m_methodInterceptor.intercept(methodInstances, this);
}
List<ITestNGMethod> result = Lists.newArrayList();
for (IMethodInstance imi : methodInstances) {
result.add(imi.getMethod());
}
//Since an interceptor is involved, we would need to ensure that the ClassMethodMap object is in sync with the
//output of the interceptor, else @AfterClass doesn't get executed at all when interceptors are involved.
//so let's update the current classMethodMap object with the list of methods obtained from the interceptor.
this.m_classMethodMap = new ClassMethodMap(result, null);
return result.toArray(new ITestNGMethod[result.size()]);
}
private List<List<IMethodInstance>> createInstances(List<IMethodInstance> methodInstances) {
Map<Object, List<IMethodInstance>> map = Maps.newHashMap();
// MapList<IMethodInstance[], Object> map = new MapList<IMethodInstance[], Object>();
for (IMethodInstance imi : methodInstances) {
for (Object o : imi.getInstances()) {
System.out.println(o);
List<IMethodInstance> l = map.get(o);
if (l == null) {
l = Lists.newArrayList();
map.put(o, l);
}
l.add(imi);
}
// for (Object instance : imi.getInstances()) {
// map.put(imi, instance);
// }
}
// return map.getKeys();
// System.out.println(map);
return new ArrayList<List<IMethodInstance>>(map.values());
}
@Override
public Injector getInjector(IClass iClass) {
Annotation annotation = AnnotationHelper.findAnnotationSuperClasses(Guice.class, iClass.getRealClass());
if (annotation == null) return null;
if (iClass instanceof TestClass) {
iClass = ((TestClass)iClass).getIClass();
}
if (!(iClass instanceof ClassImpl)) return null;
Injector parentInjector = ((ClassImpl)iClass).getParentInjector();
Guice guice = (Guice) annotation;
List<Module> moduleInstances = Lists.newArrayList(getModules(guice, parentInjector, iClass.getRealClass()));
// Reuse the previous injector, if any
Injector injector = getInjector(moduleInstances);
if (injector == null) {
injector = parentInjector.createChildInjector(moduleInstances);
addInjector(moduleInstances, injector);
}
return injector;
}
/**
* Collects and orders test or configuration methods
* @param methods methods to be worked on
* @param forTests true for test methods, false for configuration methods
* @param runInfo
* @param finder annotation finder
* @param unique true for unique methods, false otherwise
* @param outExcludedMethods
* @return list of ordered methods
*/
public static ITestNGMethod[] collectAndOrderMethods(List<ITestNGMethod> methods,
boolean forTests, RunInfo runInfo, IAnnotationFinder finder,
boolean unique, List<ITestNGMethod> outExcludedMethods)
{
List<ITestNGMethod> includedMethods = Lists.newArrayList();
MethodGroupsHelper.collectMethodsByGroup(methods.toArray(new ITestNGMethod[methods.size()]),
forTests,
includedMethods,
outExcludedMethods,
runInfo,
finder,
unique);
return sortMethods(forTests, includedMethods, finder).toArray(new ITestNGMethod[]{});
}
private void constructSegmentWithTextIndex(SegmentVersion segmentVersion)
throws Exception {
FileUtils.deleteQuietly(INDEX_DIR);
SegmentGeneratorConfig segmentGeneratorConfig =
SegmentTestUtils.getSegmentGeneratorConfigWithoutTimeColumn(_avroFile, INDEX_DIR, "testTable");
SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
List<String> textIndexCreationColumns = Lists.newArrayList(TEXT_INDEX_COL_NAME);
List<String> rawIndexCreationColumns = Lists.newArrayList(TEXT_INDEX_COL_NAME);
segmentGeneratorConfig.setTextIndexCreationColumns(textIndexCreationColumns);
segmentGeneratorConfig.setRawIndexCreationColumns(rawIndexCreationColumns);
segmentGeneratorConfig.setSegmentVersion(segmentVersion);
driver.init(segmentGeneratorConfig);
driver.build();
_indexDir = new File(INDEX_DIR, driver.getSegmentName());
}
private static List<ITestNGMethod> sortMethods(boolean forTests,
List<ITestNGMethod> allMethods, IAnnotationFinder finder) {
List<ITestNGMethod> sl = Lists.newArrayList();
List<ITestNGMethod> pl = Lists.newArrayList();
ITestNGMethod[] allMethodsArray = allMethods.toArray(new ITestNGMethod[allMethods.size()]);
// Fix the method inheritance if these are @Configuration methods to make
// sure base classes are invoked before child classes if 'before' and the
// other way around if they are 'after'
if (!forTests && allMethodsArray.length > 0) {
ITestNGMethod m = allMethodsArray[0];
boolean before = m.isBeforeClassConfiguration()
|| m.isBeforeMethodConfiguration() || m.isBeforeSuiteConfiguration()
|| m.isBeforeTestConfiguration();
MethodInheritance.fixMethodInheritance(allMethodsArray, before);
}
topologicalSort(allMethodsArray, sl, pl);
List<ITestNGMethod> result = Lists.newArrayList();
result.addAll(sl);
result.addAll(pl);
return result;
}
@Test(timeOut = 10000)
public void testGetPeerClusters() throws Exception {
// clean up peer-clusters
admin1.clusters().updatePeerClusterNames("r1", null);
admin1.clusters().updatePeerClusterNames("r2", null);
admin1.clusters().updatePeerClusterNames("r3", null);
final String mainClusterName = "r1";
assertNull(admin1.clusters().getPeerClusterNames(mainClusterName));
LinkedHashSet<String> peerClusters = Sets.newLinkedHashSet(Lists.newArrayList("r2", "r3"));
admin1.clusters().updatePeerClusterNames(mainClusterName, peerClusters);
retryStrategically((test) -> {
try {
return admin1.clusters().getPeerClusterNames(mainClusterName).size() == 1;
} catch (PulsarAdminException e) {
return false;
}
}, 5, 100);
assertEquals(admin1.clusters().getPeerClusterNames(mainClusterName), peerClusters);
}
@Test(groups = "efficiency")
@Parameters({"capacity", "passes", "generatorMultipler", "workingSetMultiplier"})
public void benchmark(int capacity, int passes, int generatorMultipler,
int workingSetMultiplier) {
Generator generator = new ScrambledZipfianGenerator(generatorMultipler * capacity);
List<List<String>> workingSets = Lists.newArrayList();
for (int i = 1; i <= passes; i++) {
int size = i * workingSetMultiplier * capacity;
workingSets.add(createWorkingSet(generator, size));
}
Set<Policy> seen = EnumSet.noneOf(Policy.class);
for (CacheType cache : CacheType.values()) {
if (!seen.add(cache.policy())) {
continue;
}
Map<String, String> map = new CacheFactory()
.maximumCapacity(capacity)
.makeCache(cache);
System.out.println(cache.policy().toString() + ":");
for (List<String> workingSet : workingSets) {
System.out.println(determineEfficiency(map, workingSet));
}
}
}
@Test
public void testListCopyableVersions() {
Properties props = new Properties();
Path dummyPath = new Path("dummy");
DateTime dt1 = new DateTime().minusDays(8);
DateTime dt2 = new DateTime().minusDays(6);
props.put(SelectAfterTimeBasedPolicy.TIME_BASED_SELECTION_LOOK_BACK_TIME_KEY, "7d");
SelectAfterTimeBasedPolicy policyLookback7Days = new SelectAfterTimeBasedPolicy(props);
TimestampedDatasetVersion version1 = new TimestampedDatasetVersion(dt1, dummyPath);
TimestampedDatasetVersion version2 = new TimestampedDatasetVersion(dt2, dummyPath);
Assert.assertEquals(policyLookback7Days.listSelectedVersions(Lists.newArrayList(version1, version2)).size(), 1);
props.put(SelectAfterTimeBasedPolicy.TIME_BASED_SELECTION_LOOK_BACK_TIME_KEY, "1h");
SelectAfterTimeBasedPolicy policyLookback1Hour = new SelectAfterTimeBasedPolicy(props);
Assert.assertEquals(policyLookback1Hour.listSelectedVersions(Lists.newArrayList(version1, version2)).size(), 0);
props.put(SelectAfterTimeBasedPolicy.TIME_BASED_SELECTION_LOOK_BACK_TIME_KEY, "9d");
SelectAfterTimeBasedPolicy policyLookback8Days = new SelectAfterTimeBasedPolicy(props);
Assert.assertEquals(policyLookback8Days.listSelectedVersions(Lists.newArrayList(version1, version2)).size(), 2);
}
@Test
public void testFailJobWhenPreviousStateExistsButDoesNotHaveSnapshot() {
try {
DummyFileBasedSource source = new DummyFileBasedSource();
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.setId("priorState");
List<WorkUnitState> workUnitStates = Lists.newArrayList(workUnitState);
State state = new State();
state.setProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY, Extract.TableType.SNAPSHOT_ONLY.toString());
state.setProp(ConfigurationKeys.SOURCE_FILEBASED_FS_PRIOR_SNAPSHOT_REQUIRED, true);
SourceState sourceState = new SourceState(state, workUnitStates);
source.getWorkunits(sourceState);
Assert.fail("Expected RuntimeException, but no exceptions were thrown.");
} catch (RuntimeException e) {
Assert.assertEquals("No 'source.filebased.fs.snapshot' found on state of prior job", e.getMessage());
}
}
@Test
public void test4() throws Exception {
ThirtyDaySearchOperator operator = new ThirtyDaySearchOperator()
.withKeywords(Lists.newArrayList("a"))
.withAnds(Lists.newArrayList(
new ThirtyDaySearchOperator()
.withKeywords(Lists.newArrayList("b"))
.withOrs(Lists.newArrayList(
new ThirtyDaySearchOperator()
.withKeywords(Lists.newArrayList("c")))
)
))
.withOrs(Lists.newArrayList(
new ThirtyDaySearchOperator()
.withKeywords(Lists.newArrayList("d"))
.withAnds(Lists.newArrayList(
new ThirtyDaySearchOperator()
.withKeywords(Lists.newArrayList("e"))
)
)
))
.withNot(true);
String query = SearchUtil.toString(operator);
Assert.assertEquals( "- ( a AND ( b OR ( c ) ) OR ( d AND ( e ) ) )", query);
}
@Test
public void testBulkEnrichment() throws Exception {
PersonEnrichment personEnrichment = PeopleDataLabs.getInstance(config);
List<String> emails = testsconfig.getStringList("testBulkEnrichment.emails");
BulkEnrichPersonRequestItem item1 = new BulkEnrichPersonRequestItem()
.withParams(new Params().withEmail(Lists.newArrayList(emails.get(0))));
BulkEnrichPersonRequestItem item2 = new BulkEnrichPersonRequestItem()
.withParams(new Params().withEmail(Lists.newArrayList(emails.get(1))));
BulkEnrichPersonRequestItem item3 = new BulkEnrichPersonRequestItem()
.withParams(new Params().withEmail(Lists.newArrayList(emails.get(2))));
List<BulkEnrichPersonRequestItem> reqList = Lists.newArrayList(item1, item2, item3);
BulkEnrichPersonRequest bulkRequest = new BulkEnrichPersonRequest().withRequests(reqList);
List<BulkEnrichPersonResponseItem> response = personEnrichment.bulkEnrichPerson(bulkRequest);
nonNull(response);
assertThat("response contains three response items", response.size() == 3);
}
@Test(enabled = false)
public void testEnrichPersonByTwitterUserid() throws Exception {
PersonEnrichment personEnrichment = FullContact.getInstance(config);
String userid = StreamsConfigurator.getConfig().getString("org.apache.streams.fullcontact.test.FullContactIT.testEnrichPersonByTwitterUserid.userid");
EnrichPersonRequest req = new EnrichPersonRequest()
.withProfiles(
Lists.newArrayList(
new ProfileQuery()
.withService("twitter")
.withUserid(userid)
)
);
PersonSummary response = personEnrichment.enrichPerson(req);
nonNull(response);
nonNull(response.getFullName());
assertThat("response contains a non-empty fullName", StringUtils.isNotBlank(response.getFullName()));
}
@Test
public void testEnrichPersonByTwitterUsername() throws Exception {
PersonEnrichment personEnrichment = FullContact.getInstance(config);
String username = StreamsConfigurator.getConfig().getString("org.apache.streams.fullcontact.test.FullContactIT.testEnrichPersonByTwitterUsername.username");
EnrichPersonRequest req = new EnrichPersonRequest()
.withProfiles(
Lists.newArrayList(
new ProfileQuery()
.withService("twitter")
.withUsername(username)
)
);
PersonSummary response = personEnrichment.enrichPerson(req);
nonNull(response);
nonNull(response.getFullName());
assertThat("response contains a non-empty fullName", StringUtils.isNotBlank(response.getFullName()));
}
@Test
public void testEnrichPersonByGithubUrl() throws Exception {
PersonEnrichment personEnrichment = FullContact.getInstance(config);
String url = StreamsConfigurator.getConfig().getString("org.apache.streams.fullcontact.test.FullContactIT.testEnrichPersonByGithubUrl.url");
EnrichPersonRequest req = new EnrichPersonRequest()
.withProfiles(
Lists.newArrayList(
new ProfileQuery()
.withService("github")
.withUrl(url)
)
);
PersonSummary response = personEnrichment.enrichPerson(req);
nonNull(response);
nonNull(response.getFullName());
assertThat("response contains a non-empty fullName", StringUtils.isNotBlank(response.getFullName()));
}
/**
* find Methods by MethodName
*
* @param clazz
* @param methodNames
* @return
*/
public static List<Method> findMethodsByName(Class<?> clazz, String... methodNames) {
if (clazz == null || methodNames == null || methodNames.length == 0) {
return null;
}
List<Method> result = Lists.newArrayList();
for (Method method : clazz.getMethods()) {
for (String methodName : methodNames) {
if (StringUtils.equals(method.getName(), methodName)) {
result.add(method);
}
}
}
return result;
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@Test
public void testHasMostApprovals() {
ProposalWrapper proposalWrapper = new ProposalWrapper(
Proposal.newBuilder().build());
proposalWrapper.setState(State.APPROVED);
proposalWrapper.setID(1);
List<ByteString> activeWitnesses = Lists.newArrayList();
for (int i = 0; i < 27; i++) {
activeWitnesses.add(ByteString.copyFrom(new byte[]{(byte) i}));
}
for (int i = 0; i < 18; i++) {
proposalWrapper.addApproval(ByteString.copyFrom(new byte[]{(byte) i}));
}
Assert.assertEquals(true, proposalWrapper.hasMostApprovals(activeWitnesses));
proposalWrapper.clearApproval();
for (int i = 1; i < 18; i++) {
proposalWrapper.addApproval(ByteString.copyFrom(new byte[]{(byte) i}));
}
activeWitnesses.clear();
for (int i = 0; i < 5; i++) {
activeWitnesses.add(ByteString.copyFrom(new byte[]{(byte) i}));
}
proposalWrapper.clearApproval();
for (int i = 0; i < 3; i++) {
proposalWrapper.addApproval(ByteString.copyFrom(new byte[]{(byte) i}));
}
Assert.assertEquals(true, proposalWrapper.hasMostApprovals(activeWitnesses));
}
@Test
public void defaultToEmptyCollectionsOnNullValueTest() throws Throwable {
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(List.class, null).isEmpty());
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(List.class, Lists.newArrayList("1")).contains("1"));
Set<Object> set = Sets.newHashSet();
set.add(1);
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Set.class, set).contains(1));
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Set.class, null).isEmpty());
Map<Object, Object> map = Maps.newHashMap();
map.put(1, 2);
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Map.class, map).containsKey(1));
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Map.class, map).containsValue(2));
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Map.class, null).isEmpty());
Object[] arr = set.toArray(new Object[set.size()]);
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Object[].class, null).length == 0);
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Object[].class, arr).length == 1);
Properties prop = new Properties();
prop.put("1", "2");
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Properties.class, prop).containsKey("1"));
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Properties.class, prop).containsValue("2"));
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Properties.class, null).isEmpty());
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Collection.class, null).isEmpty());
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(Collection.class, set).contains(1));
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(String.class, null) == null);
assertTrue(Util.defaultToEmptyCollectionsOnNullValue(String.class, "123").contentEquals("123"));
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
@DataProvider
static Object[][] testCasesAll() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(testClasses()));
result.addAll(Arrays.asList(testInterfaces()));
return result.toArray(new Object[result.size()][]);
}
/**
* @return all the @Listeners annotations found in the current class and its
* superclasses.
*/
private ListenerHolder findAllListeners(Class<?> cls) {
ListenerHolder result = new ListenerHolder();
result.listenerClasses = Lists.newArrayList();
do {
IListenersAnnotation l = m_annotationFinder.findAnnotation(cls, IListenersAnnotation.class);
if (l != null) {
Class<? extends ITestNGListener>[] classes = l.getValue();
for (Class<? extends ITestNGListener> c : classes) {
result.listenerClasses.add(c);
if (ITestNGListenerFactory.class.isAssignableFrom(c)) {
if (result.listenerFactoryClass == null) {
result.listenerFactoryClass = (Class<? extends ITestNGListenerFactory>) c;
}
else {
throw new TestNGException("Found more than one class implementing" +
"ITestNGListenerFactory:" + c + " and " + result.listenerFactoryClass);
}
}
}
}
cls = cls.getSuperclass();
} while (cls != Object.class);
return result;
}