1package test.thread;
2
3import org.testng.Assert;
4import org.testng.TestNG;
5import org.testng.annotations.Test;
6import org.testng.collections.Lists;
7import org.testng.xml.XmlClass;
8import org.testng.xml.XmlSuite;
9import org.testng.xml.XmlTest;
10
11import test.BaseTest;
12
13import java.util.Arrays;
14import java.util.HashMap;
15import java.util.List;
16import java.util.Map;
17
18public class ParallelTestTest extends BaseTest {
19
20  @Test
21  public void verifyParallelNone() {
22    verifyExpected(XmlSuite.ParallelMode.NONE, 1);
23  }
24
25  @Test
26  public void verifyParallelTests() {
27    verifyExpected(XmlSuite.ParallelMode.TESTS, 2);
28  }
29
30  @Test
31  public void verifyParallelMethods() {
32    verifyExpected(XmlSuite.ParallelMode.METHODS, 4);
33  }
34
35  @Test
36  public void verifyParallelClasses() {
37    verifyExpected(XmlSuite.ParallelMode.CLASSES, 2);
38  }
39
40  @Test
41  public void verifyParallelClassesWithFactory() {
42    verifyExpected(XmlSuite.ParallelMode.INSTANCES, 2, ParallelWithFactorySampleTest.class.getName());
43  }
44
45  @Test
46  public void verifyNonParallelClassesWithFactory() {
47    verifyExpected(XmlSuite.ParallelMode.NONE, 1, ParallelWithFactorySampleTest.class.getName());
48  }
49
50  public static final String CLASS1 = "test.thread.Test1Test";
51  public static final String CLASS2 = "test.thread.Test2Test";
52
53  private void createTest(XmlSuite xmlSuite, String className) {
54    XmlTest result = new XmlTest(xmlSuite);
55    List<XmlClass> classes = result.getXmlClasses();
56    XmlClass xmlClass = new XmlClass(className);
57    classes.add(xmlClass);
58  }
59
60  private void verifyExpected(XmlSuite.ParallelMode parallelMode, int expectedThreadCount) {
61    verifyExpected(parallelMode, expectedThreadCount, CLASS1, CLASS2);
62  }
63
64  private void verifyExpected(XmlSuite.ParallelMode parallelMode, int expectedThreadCount,
65      String... classNames) {
66    XmlSuite xmlSuite = new XmlSuite();
67    xmlSuite.setName("ParallelTestTest");
68    xmlSuite.setParallel(parallelMode);
69    for (String cn : classNames) {
70      createTest(xmlSuite, cn);
71    }
72
73    TestNG tng = new TestNG();
74    tng.setVerbose(0);
75    tng.setXmlSuites(Arrays.asList(new XmlSuite[] { xmlSuite }));
76
77    Helper.reset();
78
79    tng.run();
80
81    List<Map<Long, Long>> maps = Lists.newArrayList();
82    for (String c : classNames) {
83      maps.add(Helper.getMap(c));
84    };
85
86    Map<Long, Long> mergedMap = new HashMap<>();
87    for (Map<Long, Long>m : maps) {
88      mergedMap.putAll(m);
89    }
90
91    Assert.assertEquals(mergedMap.size(), expectedThreadCount);
92  }
93
94  private static void ppp(String s) {
95    if (false) {
96      System.out.println("[SequentialTest] " + s);
97    }
98  }
99
100}
101