@RunWith(PowerMockRunner.class) @PrepareForTest({ConfigParamManager.class, Document.class}) public class ConfigParamManagerTest { private Logger logger = Logger.getLogger(ConfigParamManagerTest.class); private static String configLocation = "environmentConfig.xml"; @BeforeClass public static void setUp() { // PropertyConfigurator.configure(ConfigParamManagerTest.class.getClassLoader().getResource("log4j.properties")); } @Test public void readConfig_A$_XML() throws Exception { // 建立私有方法的mock对象 ConfigParamManager mock = PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType"); // 录制私有方法行为 PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class)) .andReturn("XML"); // 回放mock对象行为 PowerMock.replay(mock); EnvConfigBean envConfig = mock.readConfig(); assertNotNull(envConfig); assertEquals("XML", envConfig.getConfigType()); assertEquals( "http://172.16.30.20:8090/xms/", ConfigParamMap.getConfigParamMap().get("xms_url").getValue()); PowerMock.verifyAll(); } @Test public void testReadConfig_JDBC() throws Exception { // 建立私有方法的mock对象 ConfigParamManager mock = PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType"); // 录制私有方法行为 PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class)) .andReturn("JDBC"); // 回放mock对象行为 PowerMock.replay(mock); EnvConfigBean envConfig = mock.readConfig(configLocation); assertNotNull(envConfig); assertEquals("JDBC", envConfig.getConfigType()); assertTrue(envConfig.getJdbc().keySet().size() > 0); for (ConfigDataSourceBean csb : envConfig.getJdbc().values()) { System.out.println("jdbc config==>" + csb.getName() + " = " + csb.getValue()); } for (ConfigParamBean cpb : ConfigParamMap.getConfigParamMap().values()) { System.out.println( "jdbc configParam==>" + cpb.getName() + " || " + cpb.getValue() + " || " + cpb.getSystem()); } } @Test public void testReadConfig_JNDI() throws Exception { // 建立私有方法的mock对象 ConfigParamManager mock = PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType"); // 录制私有方法行为 PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class)) .andReturn("JNDI"); // 回放mock对象行为 PowerMock.replay(mock); EnvConfigBean envConfig = mock.readConfig(configLocation); assertNotNull(envConfig); assertEquals("JNDI", envConfig.getConfigType()); assertEquals(0, envConfig.getJndi().keySet().size()); for (ConfigDataSourceBean csb : envConfig.getJndi().values()) { System.out.println("jndi config==>" + csb.getName() + " = " + csb.getValue()); } } /** @throws Exception */ @Test(expected = EnvironmentConfigException.class) public void testReadConfig_JNDI_EnvironmentConfigException() throws Exception { // 建立私有方法的mock对象 ConfigParamManager mock = PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType"); // 录制私有方法行为 PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class)) .andReturn("JNDI"); // 建立mock对象 Document mockDocument = EasyMock.createMock(Document.class); // Document a = PowerMock.createMock(Document.class); // 录制public方法行为 EasyMock.expect(mockDocument.getElementsByTagName(EasyMock.anyObject(String.class))) .andReturn(null); // 回放mock对象行为 PowerMock.replay(mock); // 回放mock对象行为 EasyMock.replay(mockDocument); EnvConfigBean envConfig = mock.readConfig(configLocation); PowerMock.verifyAll(); EasyMock.verify(mockDocument); } @Test public void testSetEnvConfigLocation() { ConfigParamManager cpm = new ConfigParamManager(); cpm.setEnvConfigLocation("abc"); assertEquals("environmentConfig.xml", cpm.getEnvConfigLocation()); } @Test public void testCustomerConfigLocation() throws Exception { // 建立私有方法的mock对象 ConfigParamManager mock = PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType"); // 录制私有方法行为 PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class)) .andReturn("XML"); // 回放mock对象行为 PowerMock.replay(mock); EnvConfigBean envConfig = mock.readConfig("test/testEnvironmentConfig.xml"); assertEquals(3, envConfig.getConfigParam().entrySet().size()); PowerMock.verifyAll(); } }
public class Login_Scenario extends Base_Class { static Logger log = Logger.getLogger(Login_Scenario.class); @Test( dataProvider = "DP_invalid_login", dataProviderClass = DataProviderObjects.DP_LoginScenario.class) public void invalid_login(String TC_ID, String Order, String Uname, String Pwd, String expected) throws Exception { SoftAssert assert1 = new SoftAssert(); log.info("Starting invalid_login scenario" + TC_ID + " " + Order); Initialize_browser(); log.info("Browser Initialized" + TC_ID + " " + Order); POM_LoginScenario pom_invalid = new POM_LoginScenario(driver); pom_invalid.execute_common_methods_log(Uname, Pwd); if (driver .getTitle() .equalsIgnoreCase( "Buy Books Online | Online Bookstore India | Online Book Shopping | Free Shipping Across India")) { log.error("The user has loggedin, the page the user currently is " + driver.getTitle()); Assert.fail(); tear_down(); } String actual = pom_invalid.get_invalid_log_msg(); // assert1.assertEquals(actual, expected ,"The actual found is"+ actual+" The expected is "+ // expected); if (actual.equalsIgnoreCase(expected)) { log.info("The validation has passed"); } else { log.error("THe validation has failed"); } tear_down(); assert1.assertAll(); log.info("Completed invalid_login scenario" + TC_ID + " " + Order); } @Test( dataProvider = "DP_valid_login", dataProviderClass = DataProviderObjects.DP_LoginScenario.class, groups = {"SmokeTest"}) public void avalid_login(String TC_ID, String Order, String Uname, String Pwd, String expected) throws Exception { SoftAssert assert1 = new SoftAssert(); Initialize_browser(); POM_LoginScenario pom_valid = new POM_LoginScenario(driver); pom_valid.execute_common_methods_log(Uname, Pwd); if (!driver .getTitle() .equalsIgnoreCase( "Buy Books Online | Online Bookstore India | Online Book Shopping | Free Shipping Across India")) { log.error( "The user has failed to login, the page the user currently is " + driver.getTitle()); Assert.fail(); tear_down(); } String actual = pom_valid.get_valid_log_msg(); assert1.assertEquals( actual, expected, "The actual found is" + actual + " The expected is " + expected); if (actual.equalsIgnoreCase(expected)) { log.info("The validation has passed"); } else { log.error("THe validation has failed"); } pom_valid.click_signout(); tear_down(); assert1.assertAll(); } }
public class ClusterEntityHelperImpl extends IEntityManagerHelper { public ClusterEntityHelperImpl() {} public ClusterEntityHelperImpl(String envFileName) throws Exception { super(envFileName); } Logger logger = Logger.getLogger(this.getClass()); public ServiceResponse delete(String url, String data) throws Exception { // throw new UnsupportedOperationException("Not supported yet."); url += "/cluster/" + Util.readClusterName(data) + colo; return Util.sendRequest(url); } public ServiceResponse getEntityDefinition(String url, String data) throws Exception { url += "/cluster/" + Util.readClusterName(data); return Util.sendRequest(url); } public ServiceResponse getStatus(String url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse getStatus(Util.URLS url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse resume(String url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse schedule(String url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse submitAndSchedule(String url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse submitAndSchedule(Util.URLS url, String data) throws Exception { return null; } public ServiceResponse submitEntity(String url, String data) throws Exception { // throw new UnsupportedOperationException("Not supported yet."); url += "/cluster" + colo; return Util.sendRequest(url, data); } public ServiceResponse suspend(String url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse suspend(Util.URLS url, String data) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public ServiceResponse validateEntity(String url, String data) throws Exception { return Util.sendRequest(url, data); } public void validateResponse(String response, APIResult.Status expectedResponse, String filename) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public ServiceResponse submitEntity(Util.URLS url, String data) throws Exception { // TODO Auto-generated method stub // throw new UnsupportedOperationException("Not supported yet."); return submitEntity(this.hostname + url.getValue(), data); } @Override public ServiceResponse schedule(Util.URLS scheduleUrl, String processData) throws Exception { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not supported yet."); } @Override public ServiceResponse delete(Util.URLS deleteUrl, String data) throws Exception { // TODO Auto-generated method stub return delete(this.hostname + deleteUrl.getValue(), data); } @Override public ServiceResponse resume(Util.URLS url, String data) throws Exception { // TODO Auto-generated method stub return null; } public ProcessInstancesResult getRunningInstance(Util.URLS processRuningInstance, String name) throws Exception { // TODO Auto-generated method stub return null; } public ProcessInstancesResult getProcessInstanceStatus(String readEntityName, String params) { // TODO Auto-generated method stub return null; } public ProcessInstancesResult getProcessInstanceSuspend(String readEntityName, String params) { // TODO Auto-generated method stub return null; } public String writeEntityToFile(String entity) throws Exception { File file = new File("/tmp/" + Util.readClusterName(entity) + ".xml"); BufferedWriter bf = new BufferedWriter(new FileWriter(file)); bf.write(entity); bf.close(); return "/tmp/" + Util.readClusterName(entity) + ".xml"; } @Override public String submitEntityViaCLI(String filePath) throws Exception { // System.out.println(BASE_COMMAND+ " entity -submit -url "+this.hostname+" -type cluster // -file "+filePath); return Util.executeCommand( BASE_COMMAND + " entity -submit -url " + this.hostname + " -type cluster -file " + filePath); } @Override public String validateEntityViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -validate -url " + this.hostname + " -type cluster -name " + entityName); } @Override public String submitAndScheduleViaCLI(String filePath) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -submitAndSchedule -url " + this.hostname + " -type cluster -file " + filePath); } @Override public String scheduleViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -schedule -url " + this.hostname + " -type cluster -name " + entityName); } @Override public String resumeViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -resume -url " + this.hostname + " -type cluster -name " + entityName); } @Override public String getStatusViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -status -url " + this.hostname + " -type cluster -name " + entityName); } @Override public String getEntityDefinitionViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -definition -url " + this.hostname + " -type cluster -name " + entityName); } @Override public String deleteViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -delete -url " + this.hostname + " -type cluster -name " + entityName); } @Override public String suspendViaCLI(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -suspend -url " + this.hostname + " -type cluster -name " + entityName); } public String updateViaCLI(String processName, String newProcessFilePath) throws Exception { return null; } public String list() throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -list -url " + this.hostname + " -type cluster"); } @Override public String getDependencies(String entityName) throws Exception { return Util.executeCommand( BASE_COMMAND + " entity -dependency -url " + this.hostname + " -type cluster -name " + entityName); } @Override public ProcessInstancesResult getRunningInstance(String processRuningInstance, String name) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<String> getArchiveInfo() throws Exception { return Util.getClusterArchiveInfo(this); } @Override public List<String> getStoreInfo() throws Exception { return Util.getClusterStoreInfo(this); } @Override public ServiceResponse getEntityDefinition(Util.URLS url, String data) throws Exception { return getEntityDefinition(this.hostname + url.getValue(), data); } @Override public ServiceResponse update(String oldEntity, String newEntity) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public String toString(Object object) throws Exception { Cluster processObject = (Cluster) object; JAXBContext context = JAXBContext.newInstance(Cluster.class); Marshaller um = context.createMarshaller(); StringWriter writer = new StringWriter(); um.marshal(processObject, writer); return writer.toString(); } @Override public ProcessInstancesResult getInstanceRerun(String EntityName, String params) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public ProcessInstancesResult getProcessInstanceKill(String readEntityName, String string) throws Exception { // TODO Auto-generated method stub return null; } @Override public ProcessInstancesResult getProcessInstanceRerun(String readEntityName, String string) throws Exception { // TODO Auto-generated method stub return null; } @Override public ProcessInstancesResult getProcessInstanceResume(String readEntityName, String string) throws Exception { // TODO Auto-generated method stub return null; } @Override public String getProcessInstanceStatusViaCli( String EntityName, String start, String end, String colos) throws Exception { // TODO Auto-generated method stub return null; } }
/** * This class represents a test class: - The test methods - The configuration methods (test and * method) - The class file * * @author <a href="mailto:[email protected]">Cedric Beust</a> * @author <a href='mailto:[email protected]'>Alexandru Popescu</a> */ class TestClass extends NoOpTestClass implements ITestClass { /* generated */ private static final long serialVersionUID = -8077917128278361294L; private transient IAnnotationFinder annotationFinder = null; // The Strategy used to locate test methods (TestNG, JUnit, etc...) private transient ITestMethodFinder testMethodFinder = null; private IClass iClass = null; private String testName; private XmlTest xmlTest; private XmlClass xmlClass; private static final Logger LOG = Logger.getLogger(TestClass.class); protected TestClass( IClass cls, ITestMethodFinder testMethodFinder, IAnnotationFinder annotationFinder, RunInfo runInfo, XmlTest xmlTest, XmlClass xmlClass) { init(cls, testMethodFinder, annotationFinder, xmlTest, xmlClass); } @Override public String getTestName() { return testName; } @Override public XmlTest getXmlTest() { return xmlTest; } @Override public XmlClass getXmlClass() { return xmlClass; } public IAnnotationFinder getAnnotationFinder() { return annotationFinder; } private void init( IClass cls, ITestMethodFinder testMethodFinder, IAnnotationFinder annotationFinder, XmlTest xmlTest, XmlClass xmlClass) { log(3, "Creating TestClass for " + cls); iClass = cls; m_testClass = cls.getRealClass(); this.xmlTest = xmlTest; this.xmlClass = xmlClass; this.testMethodFinder = testMethodFinder; this.annotationFinder = annotationFinder; initTestClassesAndInstances(); initMethods(); } private void initTestClassesAndInstances() { // // TestClasses and instances // Object[] instances = getInstances(false); for (Object instance : instances) { if (instance instanceof ITest) { testName = ((ITest) instance).getTestName(); break; } } if (testName == null) { testName = iClass.getTestName(); } } @Override public Object[] getInstances(boolean create) { return iClass.getInstances(create); } @Override public long[] getInstanceHashCodes() { return iClass.getInstanceHashCodes(); } @Deprecated @Override public int getInstanceCount() { return iClass.getInstanceCount(); } @Override public void addInstance(Object instance) { iClass.addInstance(instance); } private void initMethods() { ITestNGMethod[] methods = testMethodFinder.getTestMethods(m_testClass, xmlTest); m_testMethods = createTestMethods(methods); for (Object instance : iClass.getInstances(false)) { m_beforeSuiteMethods = ConfigurationMethod.createSuiteConfigurationMethods( testMethodFinder.getBeforeSuiteMethods(m_testClass), annotationFinder, true, instance); m_afterSuiteMethods = ConfigurationMethod.createSuiteConfigurationMethods( testMethodFinder.getAfterSuiteMethods(m_testClass), annotationFinder, false, instance); m_beforeTestConfMethods = ConfigurationMethod.createTestConfigurationMethods( testMethodFinder.getBeforeTestConfigurationMethods(m_testClass), annotationFinder, true, instance); m_afterTestConfMethods = ConfigurationMethod.createTestConfigurationMethods( testMethodFinder.getAfterTestConfigurationMethods(m_testClass), annotationFinder, false, instance); m_beforeClassMethods = ConfigurationMethod.createClassConfigurationMethods( testMethodFinder.getBeforeClassMethods(m_testClass), annotationFinder, true, instance); m_afterClassMethods = ConfigurationMethod.createClassConfigurationMethods( testMethodFinder.getAfterClassMethods(m_testClass), annotationFinder, false, instance); m_beforeGroupsMethods = ConfigurationMethod.createBeforeConfigurationMethods( testMethodFinder.getBeforeGroupsConfigurationMethods(m_testClass), annotationFinder, true, instance); m_afterGroupsMethods = ConfigurationMethod.createAfterConfigurationMethods( testMethodFinder.getAfterGroupsConfigurationMethods(m_testClass), annotationFinder, false, instance); m_beforeTestMethods = ConfigurationMethod.createTestMethodConfigurationMethods( testMethodFinder.getBeforeTestMethods(m_testClass), annotationFinder, true, instance); m_afterTestMethods = ConfigurationMethod.createTestMethodConfigurationMethods( testMethodFinder.getAfterTestMethods(m_testClass), annotationFinder, false, instance); } } /** * 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 : iClass.getInstances(false)) { log(4, "Adding method " + tm + " on TestClass " + m_testClass); vResult.add( new TestNGMethod( /* tm.getRealClass(), */ m.getMethod(), annotationFinder, xmlTest, o)); } } else { log(4, "Rejecting method " + tm + " for TestClass " + m_testClass); } } return vResult.toArray(new ITestNGMethod[vResult.size()]); } public ITestMethodFinder getTestMethodFinder() { return testMethodFinder; } private void log(int level, String s) { Utils.log("TestClass", level, s); } protected void dump() { LOG.info("===== Test class\n" + m_testClass.getName()); for (ITestNGMethod m : m_beforeClassMethods) { LOG.info(" @BeforeClass " + m); } for (ITestNGMethod m : m_beforeTestMethods) { LOG.info(" @BeforeMethod " + m); } for (ITestNGMethod m : m_testMethods) { LOG.info(" @Test " + m); } for (ITestNGMethod m : m_afterTestMethods) { LOG.info(" @AfterMethod " + m); } for (ITestNGMethod m : m_afterClassMethods) { LOG.info(" @AfterClass " + m); } LOG.info("======"); } @Override public String toString() { return Objects.toStringHelper(getClass()).add("name", m_testClass).toString(); } public IClass getIClass() { return iClass; } }
public class CreditCardTestCase { private static final Logger logger = Logger.getLogger(CreditCardTestCase.class); public CreditCard creditCard; public static String createdCreditCardId = null; public static final String TYPE = "visa"; public static final String NUMBER = "4329685037393232"; public static final String FIRSTNAME = "Joe"; public static final String LASTNAME = "Shopper"; public static final int EXPMONTH = 11; public static final int EXPYEAR = 2018; public static final int CVV2 = 874; public static final String ID = "12345"; public static final String EXTERNAL_CUSTOMER_ID = "12345"; public static final String STATE = "Approved"; public static final String VALIDUNTIL = "2020"; public static final Address BILLINGADDRESS = AddressTestCase.createAddress(); @BeforeTest(groups = "integration") public void beforeClass() throws PayPalRESTException { File testFile = new File(".", "src/test/resources/sdk_config.properties"); PayPalResource.initConfig(testFile); String clientID = "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM"; String clientSecret = "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"; TokenHolder.accessToken = new OAuthTokenCredential(clientID, clientSecret).getAccessToken(); } public static CreditCard createCreditCard() { CreditCard creditCard = new CreditCard(); creditCard .setBillingAddress(BILLINGADDRESS) .setExpireMonth(EXPMONTH) .setExpireYear(EXPYEAR) .setFirstName(FIRSTNAME) .setLastName(LASTNAME) .setNumber(NUMBER) .setType(TYPE) .setCvv2(CVV2) .setBillingAddress(BILLINGADDRESS) .setId(ID) .setState(STATE) .setValidUntil(VALIDUNTIL); return creditCard; } public static CreditCard createDummyCreditCard() { CreditCard creditCard = new CreditCard(); creditCard.setBillingAddress(BILLINGADDRESS); creditCard.setExpireMonth(EXPMONTH); creditCard.setExpireYear(EXPYEAR); creditCard.setFirstName(FIRSTNAME); creditCard.setLastName(LASTNAME); creditCard.setNumber(NUMBER); creditCard.setType(TYPE); creditCard.setCvv2(CVV2); creditCard.setBillingAddress(BILLINGADDRESS); creditCard.setId(ID); creditCard.setExternalCustomerId(EXTERNAL_CUSTOMER_ID); creditCard.setState(STATE); creditCard.setValidUntil(VALIDUNTIL); List<Links> links = new ArrayList<Links>(); links.add(LinksTestCase.createLinks()); creditCard.setLinks(links); return creditCard; } @Test(groups = "unit") public void testConstruction() { CreditCard creditCard = createDummyCreditCard(); Assert.assertEquals(creditCard.getCvv2(), CVV2); Assert.assertEquals(creditCard.getExpireMonth(), EXPMONTH); Assert.assertEquals(creditCard.getExpireYear(), EXPYEAR); Assert.assertEquals(creditCard.getFirstName(), FIRSTNAME); Assert.assertEquals(creditCard.getLastName(), LASTNAME); Assert.assertEquals(creditCard.getNumber(), NUMBER); Assert.assertEquals(creditCard.getType(), TYPE); Assert.assertEquals(creditCard.getBillingAddress().getCity(), AddressTestCase.CITY); Assert.assertEquals(creditCard.getId(), ID); Assert.assertEquals(creditCard.getExternalCustomerId(), EXTERNAL_CUSTOMER_ID); Assert.assertEquals(creditCard.getState(), STATE); Assert.assertEquals(creditCard.getValidUntil(), VALIDUNTIL); Assert.assertEquals(creditCard.getLinks().size(), 1); } @Test(groups = "unit") public void testCvv2() { logger.info("**** Test CreditCard CVV2 ****"); CreditCard creditCard = createDummyCreditCard(); // empty CVV2 creditCard.setCvv2(null); Assert.assertEquals(-1, creditCard.getCvv2()); // valid CVV2 creditCard.setCvv2(123); Assert.assertEquals(123, creditCard.getCvv2()); } @Test(groups = "integration") public void createCreditCardTest() throws PayPalRESTException { logger.info("**** Create CreditCard ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); CreditCard creditCard = new CreditCard(); creditCard.setExpireMonth(EXPMONTH); creditCard.setExpireYear(EXPYEAR); creditCard.setNumber(NUMBER); creditCard.setType(TYPE); this.creditCard = creditCard.create(TokenHolder.accessToken); logger.info("Request = " + CreditCard.getLastRequest()); logger.info("Response = " + CreditCard.getLastResponse()); logger.info("Credit Card created with ID = " + this.creditCard.getId()); Assert.assertEquals(true, "ok".equalsIgnoreCase(this.creditCard.getState())); logger.info("Created Credit Card status = " + this.creditCard.getState()); createdCreditCardId = this.creditCard.getId(); } @Test( groups = "integration", dependsOnMethods = {"createCreditCardTest"}) public void testGetCreditCard() throws PayPalRESTException { logger.info("**** Get CreditCard ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); CreditCard retrievedCreditCard = CreditCard.get(TokenHolder.accessToken, createdCreditCardId); logger.info("Request = " + CreditCard.getLastRequest()); logger.info("Response = " + CreditCard.getLastResponse()); Assert.assertEquals( true, this.creditCard.getId().equalsIgnoreCase(retrievedCreditCard.getId())); logger.info("Retrieved Credit Card status = " + retrievedCreditCard.getState()); } @Test( groups = "integration", dependsOnMethods = {"testGetCreditCard"}) public void testUpdateCreditCard() throws PayPalRESTException { logger.info("**** Update CreditCard ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); // set up patch request Patch patch = new Patch(); patch.setOp("replace"); patch.setPath("/expire_year"); patch.setValue(new Integer(2020)); List<Patch> patchRequest = new ArrayList<Patch>(); patchRequest.add(patch); // send patch request CreditCard creditCard = new CreditCard(); creditCard.setId(createdCreditCardId); CreditCard retrievedCreditCard = creditCard.update(TokenHolder.accessToken, patchRequest); logger.info("Request = " + CreditCard.getLastRequest()); logger.info("Response = " + CreditCard.getLastResponse()); Assert.assertEquals(2020, retrievedCreditCard.getExpireYear()); } @Test( groups = "integration", dependsOnMethods = {"testUpdateCreditCard"}) public void deleteCreditCard() throws PayPalRESTException { logger.info("**** Delete CreditCard ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); CreditCard retrievedCreditCard = CreditCard.get(TokenHolder.accessToken, createdCreditCardId); retrievedCreditCard.delete(TokenHolder.accessToken); logger.info("Request = " + CreditCard.getLastRequest()); logger.info("Response = " + CreditCard.getLastResponse()); try { CreditCard.get(TokenHolder.accessToken, createdCreditCardId); } catch (Exception e) { e.printStackTrace(); } } @Test( groups = "integration", dependsOnMethods = {"createCreditCardTest"}) public void testListCreditCard() throws PayPalRESTException { logger.info("**** List CreditCard ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); CreditCardHistory creditCards = CreditCard.list(TokenHolder.accessToken); logger.info("Request = " + CreditCard.getLastRequest()); logger.info("Response = " + CreditCard.getLastResponse()); logger.info("Retrieved list of credit cards = " + creditCards.getItems()); Assert.assertTrue(creditCards.getTotalItems() > 0); } @Test( groups = "integration", dependsOnMethods = {"testGetCreditCard"}) public void getCreditCardForNull() { logger.info("**** Get CreditCard Null ****"); logger.info("Generated Access Token = " + TokenHolder.accessToken); try { CreditCard.get(TokenHolder.accessToken, null); } catch (IllegalArgumentException e) { Assert.assertTrue(e != null, "Illegal Argument Exception not thrown for null arguments"); } catch (PayPalRESTException e) { Assert.fail(); } } @Test public void testCreditCardUnknownFileConfiguration() { try { CreditCard.initConfig(new File("unknown.properties")); } catch (PayPalRESTException e) { Assert.assertEquals(e.getCause().getClass().getSimpleName(), "FileNotFoundException"); } } @Test public void testCreditCardInputStreamConfiguration() { try { File testFile = new File(".", "src/test/resources/sdk_config.properties"); FileInputStream fis = new FileInputStream(testFile); CreditCard.initConfig(fis); } catch (PayPalRESTException e) { Assert.fail("[sdk_config.properties] stream loading failed"); } catch (FileNotFoundException e) { Assert.fail("[sdk_config.properties] file is not available"); } } @Test public void testCreditCardPropertiesConfiguration() { try { File testFile = new File(".", "src/test/resources/sdk_config.properties"); Properties props = new Properties(); FileInputStream fis = new FileInputStream(testFile); props.load(fis); CreditCard.initConfig(props); } catch (FileNotFoundException e) { Assert.fail("[sdk_config.properties] file is not available"); } catch (IOException e) { Assert.fail("[sdk_config.properties] file is not loaded into properties"); } } @Test public void testTOJSON() { CreditCard creditCard = createCreditCard(); Assert.assertEquals(creditCard.toJSON().length() == 0, false); } @Test public void testTOString() { CreditCard creditCard = createCreditCard(); Assert.assertEquals(creditCard.toString().length() == 0, false); } }
public SystemAdminUsersPageTest() { log = Logger.getLogger(SystemAdminUsersPageTest.class); }
public class CmsUtilTest { private CmsUtil util = new CmsUtil(); CmsCISimple ciSimple = new CmsCISimple(); private Map<String, String> ciAttributes; private static final String CLASS_NAME = null; private static final long CI_ID = 100; private static final String CI_NAME = "Source"; private static final String NS_PATH = "/public/main"; private static final String CI_IMPL = "java.lang"; private static final String DE_FACTO = "df"; private static final String DE_JURE = "dj"; private static final Logger logger = Logger.getLogger(CmsUtilTest.class); public CmsUtilTest() { this.ciAttributes = new HashMap<String, String>(3); this.ciAttributes.put("A", "1"); this.ciAttributes.put("B", "2"); this.ciAttributes.put("Z", "26"); this.ciSimple.setCiClassName(CLASS_NAME); this.ciSimple.setCiId(CI_ID); this.ciSimple.setCiName(CI_NAME); this.ciSimple.setCreated(new Date()); this.ciSimple.setImpl(CI_IMPL); this.ciSimple.setNsPath(NS_PATH); this.ciSimple.setCiAttributes(ciAttributes); } // TODO @Test public void custCiSimpleToCi() { CmsCI ci = util.custCISimple2CI(this.ciSimple, DE_FACTO); } private void dumpCmsCIAttributes(CmsCI ci) { for (CmsCIAttribute manifestAttr : ci.getAttributes().values()) { System.out.println("~Ci_Dj :" + manifestAttr.getDjValue()); } } private void dumpMaps( Map<String, String> cloudVars, Map<String, String> globalVars, Map<String, String> localVars) { System.out.println("~CLOUDVARS " + cloudVars); System.out.println("~GLOBALVARS " + globalVars); System.out.println("~LOCALVARS " + localVars); } @Test /** * substitute cloud , global and local variables where each is simply a variable easy test to pass */ public void processAllVarsTest() { String[] cloudValues = new String[] {"cbar", "cfoo", "cbaz"}; String[] globalValues = new String[] {"gbat", "gfee", "gbiz"}; String[] localValues = new String[] {"lbaz", "lfuu", "lbuz"}; // -cloud variables are just the variable name set to upper case Map<String, String> cloudVars = new HashMap<String, String>(3); for (String val : cloudValues) { cloudVars.put(val, val.toUpperCase()); } logger.info("cloud values have been set too: " + cloudVars); Map<String, String> globalVars = new HashMap<String, String>(3); for (String val : globalValues) { globalVars.put(val, val.toUpperCase()); } logger.info("globalVars values have been set too: " + globalVars); Map<String, String> localVars = new HashMap<String, String>(3); for (String val : localValues) { localVars.put(val, val.toUpperCase()); } logger.info("local values have been set too: " + localVars); CmsCI ci = new CmsCI(); ci.setCiId(4444); ci.setCiName("processAllVarsTest"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(cloudValues.length * 3); /// set up the ci with attributes which each need replacing... int i = 0; for (String cloudVariable : cloudValues) { // 3 cloud vars CmsCIAttribute attrC = new CmsCIAttribute(); attrC.setDjValue("$OO_CLOUD{" + cloudVariable + "}"); attrC.setAttributeName("pav1"); attributes.put("cloud_" + (++i), attrC); } for (String globalVariable : globalValues) { // 3 globals CmsCIAttribute attrH = new CmsCIAttribute(); attrH.setDjValue("$OO_GLOBAL{" + globalVariable + "}"); attrH.setAttributeName("pav2"); attributes.put("global_" + (++i), attrH); } for (String localVariable : localValues) { // 3 locals CmsCIAttribute attrI = new CmsCIAttribute(); attrI.setDjValue("$OO_LOCAL{" + localVariable + "}"); attrI.setAttributeName("pav3"); attributes.put("local_" + (++i), attrI); } ci.setAttributes(attributes); logger.info("CI Attributes have been set into the ci, attrs: " + attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("after>" + djKey + "->" + djAfter); if (djKey.startsWith("cloud_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_CLOUD{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } else { if (djKey.startsWith("global_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_GLOBAL{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } else { if (djKey.startsWith("local_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_LOCAL{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } } } } } @Test /** test that a global value can refer to a cloud variable */ public void processGlobalValueWithCloudValueResolution() { String[] cloudValues = new String[] {"czat", "czitCCC"}; String[] globalValues = new String[] {"czit"}; // map to czitCCC in cloud // -cloud variables are just the variable name set to upper case Map<String, String> cloudVars = new HashMap<String, String>(3); for (String val : cloudValues) { cloudVars.put(val, val.toUpperCase()); } logger.info("cloud values have been set too: " + cloudVars); Map<String, String> globalVars = new HashMap<String, String>(3); for (String val : globalValues) { globalVars.put( val, "$OO_CLOUD{" + val + "CCC}" // is a reference to a cloud variable ); } logger.info("globalVars values have been set too: " + globalVars); CmsCI ci = new CmsCI(); ci.setCiId(9876); ci.setCiName("processGlobalValueWithCloudValueResolution"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(cloudValues.length * 3); /// set up the ci with attributes which each need replacing... int i = 0; for (String cloudVariable : cloudValues) { // 3 cloud vars CmsCIAttribute attrC = new CmsCIAttribute(); attrC.setDjValue("$OO_CLOUD{" + cloudVariable + "}"); attributes.put("cloud_" + (++i), attrC); } for (String globalVariable : globalValues) { // 3 globals CmsCIAttribute attrG = new CmsCIAttribute(); attrG.setDjValue("$OO_GLOBAL{" + globalVariable + "}"); attrG.setAttributeName("djdj"); attributes.put("global_" + (++i), attrG); } ci.setAttributes(attributes); logger.info("CI Attributes have been set into the ci, attrs: " + attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, globalVars, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, globalVars, new HashMap<String, String>()); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("after>" + djKey + "->" + djAfter); if (djKey.startsWith("cloud_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_CLOUD{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } else { if (djKey.startsWith("global_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_GLOBAL{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } } } } @Test /** test that local variable can refer to a global variable value */ public void processLocalValueWithGlobalValueResolution() { String[] globalValues = new String[] {"ggyp-Global"}; // - global variables' values are just the variable name set to upper case Map<String, String> globalVars = new HashMap<String, String>(3); for (String val : globalValues) { globalVars.put(val, val.toUpperCase()); } System.out.println("globalVars values have been set to : " + globalVars); Map<String, String> localVars = new LinkedHashMap<String, String>(2); localVars.put("myLocalScalar", "abcdefg"); localVars.put( "myLocalVariable", // one local variable refers to global "$OO_GLOBAL{ggyp-Global}" // is a reference to the global variable ); System.out.println("localVars values have been set too: " + localVars); CmsCI ci = new CmsCI(); ci.setCiId(135791113); ci.setCiName("processLocalValueWithGlobalValueResolution"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); /// set up the ci with attributes which each need replacing... int i = 0; CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_LOCAL{myLocalVariable}"); attrL.setAttributeName("pl11"); attributes.put("l81_" + (++i), attrL); CmsCIAttribute attrL2 = new CmsCIAttribute(); attrL2.setDjValue("$OO_LOCAL{myLocalScalar}"); attrL2.setAttributeName("pl22"); attributes.put("l82_" + (++i), attrL2); ci.setAttributes(attributes); System.out.println( "*****CI Attributes have been set into the ci, attrs: " + attributes.values()); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, globalVars, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, new HashMap<String, String>(), globalVars, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("after>" + djKey + "->" + djAfter); if (djKey.startsWith("global_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_GLOBAL{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } else { if (djKey.startsWith("local_")) { String expected = attributesBefore .get(djKey) .getDjValue() .replace("OO_LOCAL{", "") .replace("}", "") .toUpperCase(); assertEquals(djAfter, expected, "did not measure up for key " + djKey); } } } } @Test(priority = 89) /** * test that 1 local variable can refer to a global variable (g2) which in turn refers to a Cloud * variable (c2) while another (justX) is both in Cloud and Global variable */ public void processLocalValueWithGlobalAndCloudValueResolution() { // Variables for cloud, global, and locals Map<String, String> cloudVars = new HashMap<String, String>(3); cloudVars.put("justX", "ca"); cloudVars.put("p2", "cb"); Map<String, String> globalVars = new HashMap<String, String>(3); globalVars.put("justX", "ga"); globalVars.put("p2", "$OO_CLOUD{p2}"); Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("l1", "$OO_GLOBAL{p2}"); // want 'ca' localVars.put("p2", "$OO_GLOBAL{justX}"); // want 'ga' not 'ca' CmsCI ci = new CmsCI(); ci.setCiId(89); ci.setCiName("processLocalValueWithGlobalAndCloudValueResolution"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_LOCAL{l1}"); attrL.setAttributeName("fo"); attributes.put("firstOne", attrL); CmsCIAttribute attrL2 = new CmsCIAttribute(); attrL2.setDjValue("$OO_LOCAL{p2}"); attrL2.setAttributeName("SO"); attributes.put("secondOne", attrL2); CmsCIAttribute attrL3 = new CmsCIAttribute(); attrL3.setDjValue("$OO_GLOBAL{p2}"); attrL3.setAttributeName("TO"); attributes.put("thirdOne", attrL3); ci.setAttributes(attributes); System.out.println( "*****CI Attributes have been set into the ci, attrs: " + attributes.values()); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals("firstOne")) { assertEquals(djAfter, "cb", "firstOne was not resolved correctly, local>global>cloud"); } if (djKey.equals("secondOne")) { assertEquals(djAfter, "ga", "secondOne was not resolved correctly, local>global"); } if (djKey.equals("thirdOne")) { assertEquals(djAfter, "cb", "thirdOne was not resolved correctly, global>cloud"); } } } @Test(priority = 90) /** * test local var where both Cloud and Global have that variable name and the one we want is from * the Cloud */ public void processLocalVarChoiceGlobalVsCloud() { // Variables for cloud, global, and locals Map<String, String> cloudVars = new HashMap<String, String>(3); cloudVars.put("common", "duolc"); Map<String, String> globalVars = new HashMap<String, String>(3); globalVars.put("common", "labolg"); Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("common", "lacol"); CmsCI ci = new CmsCI(); ci.setCiId(90); ci.setCiName("processLocalVarChoiceGlobalVsCloud"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); int i = 0; CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_CLOUD{common}"); String nameOfAttribute = "my-one-attr"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "duolc"); } } } @Test(priority = 95) /** test local var where regex matches in middle not start */ public void processLocalVarMid() { Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("mylocal", "123456"); CmsCI ci = new CmsCI(); ci.setCiId(95); ci.setCiName("processLocalVarMid"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); int i = 0; CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("/preamble/$OO_LOCAL{mylocal}"); String nameOfAttribute = "my-only-attr"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "/preamble/123456"); } } } @Test(priority = 98) /** test local var where regex matches in middle not start */ public void processLocalVarDuo() { Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("mylocal", "123456"); CmsCI ci = new CmsCI(); ci.setCiId(98); ci.setCiName("processLocalVarDuo"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); int i = 0; CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("/preamble/$OO_LOCAL{mylocal}/middle/$OO_LOCAL{mylocal}"); String nameOfAttribute = "my-only-attr"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "/preamble/123456/middle/123456"); } } } @Test(priority = 111) /** test a composite var , one of each layer */ public void processLocalVarMixed() { Map<String, String> cloudVars = new HashMap<String, String>(3); cloudVars.put("myCloud", "987654"); Map<String, String> globalVars = new HashMap<String, String>(3); globalVars.put("myGlobal", "1212"); Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("myLocal", "8989"); CmsCI ci = new CmsCI(); ci.setCiId(111); ci.setCiName("processLocalVarMixed"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue( "/preamble/$OO_CLOUD{myCloud}/middle/$OO_GLOBAL{myGlobal}/sss/$OO_LOCAL{myLocal}"); String nameOfAttribute = "myMixedAttribute"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "/preamble/987654/middle/1212/sss/8989"); } } } @Test(priority = 115) /** * test multi resolution as in artifacts usage * $OO_LOCAL{groupId}:$OO_LOCAL{artifactId}:$OO_LOCAL{extension} */ public void processLocalVarTrips() { Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("groupId", "esb"); localVars.put("artifactId", "service"); localVars.put("extension", "html"); CmsCI ci = new CmsCI(); ci.setCiId(115); ci.setCiName("processLocalVarTrips"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_LOCAL{groupId}:$OO_LOCAL{artifactId}:$OO_LOCAL{extension}"); String nameOfAttribute = "myArtifactGav"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "esb:service:html"); } } } @Test(priority = 122) /** test variable that is not one of our OO_CLOUD/LOCAL/GLOBAL varieties */ public void processLocalVarNegativeSpelling() { Map<String, String> localVars = new HashMap<String, String>(1); localVars.put("groupId", "barrrrrr"); CmsCI ci = new CmsCI(); ci.setCiId(122); ci.setCiName("processLocalVarNegativeSpelling"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_NOOCAL{groupId}"); // typo in place of $OO_LOCAL String nameOfAttribute = "irrelevantname"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "$OO_NOOCAL{groupId}"); // outcome is it stays as it } } } @Test(priority = 130, expectedExceptions = CIValidationException.class) /** test variable that user did not set, it is exception bad reference */ public void processLocalVarNegativeMissingLocal() { Map<String, String> localVars = new HashMap<String, String>(1); localVars.put("aaaaaa", "ignore-me"); CmsCI ci = new CmsCI(); ci.setCiId(130); ci.setCiName("processLocalVarNegativeMissingLocal"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_LOCAL{this-is-not-resolved}"); String nameOfAttribute = "trouble"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, localVars); dumpCmsCIAttributes(ci); } @Test(priority = 131, expectedExceptions = CIValidationException.class) /** test variable that user did not set, it is exception bad reference */ public void processLocalVarNegativeMissingLocal2() { CmsCI ci = new CmsCI(); ci.setCiId(132); ci.setCiName("processLocalVarNegativeMissingLocal2"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_LOCAL{this-is-not-resolved}"); String nameOfAttribute = "trouble"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, null); // this time all map empty dumpCmsCIAttributes(ci); } @Test(priority = 132, expectedExceptions = CIValidationException.class) /** test variable that user did not set, it is exception bad reference */ public void processLocalVarNegativeMissingGlobal() { CmsCI ci = new CmsCI(); ci.setCiId(132); ci.setCiName("processLocalVarNegativeMissingGlobal"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_GLOBAL{where-is-it}"); String nameOfAttribute = "nowhere"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, null); dumpCmsCIAttributes(ci); } @Test(priority = 132, expectedExceptions = CIValidationException.class) /** test variable that user did not set, it is exception bad reference */ public void processLocalVarNegativeMissingGlobal2() { Map<String, String> globalVars = new HashMap<String, String>(1); globalVars.put("cc", "ignore-distraction"); CmsCI ci = new CmsCI(); ci.setCiId(132); ci.setCiName("processLocalVarNegativeMissingGlobal2"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_GLOBAL{where?}"); String nameOfAttribute = "nowh---ere"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, globalVars, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, globalVars, null); dumpCmsCIAttributes(ci); } @Test(priority = 133, expectedExceptions = CIValidationException.class) /** test variable that user did not set, it is exception bad reference */ public void processLocalVarNegativeMissingCloud1() { Map<String, String> cloudVars = new HashMap<String, String>(1); cloudVars.put("bb", "ignore-bb"); CmsCI ci = new CmsCI(); ci.setCiId(133); ci.setCiName("processLocalVarNegativeMissingCloud1"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_CLOUD{not-cloudy}"); String nameOfAttribute = "sun"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, null, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, null, null); dumpCmsCIAttributes(ci); } @Test(priority = 134, expectedExceptions = CIValidationException.class) /** test variable that user did not set, it is exception bad reference */ public void processLocalVarNegativeMissingCloud() { CmsCI ci = new CmsCI(); ci.setCiId(134); ci.setCiName("processLocalVarNegativeMissingCloud"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_CLOUD{not-cloudy}"); String nameOfAttribute = "sun"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, null, null, null); dumpCmsCIAttributes(ci); } @Test(priority = 140) /** * test multi resolution as in artifacts usage * $OO_LOCAL{groupId}:$OO_LOCAL{artifactId}:$OO_LOCAL{extension} */ public void processLocalVarDemo() { Map<String, String> cloudVars = new HashMap<String, String>(3); cloudVars.put("version", "2.0"); Map<String, String> globalVars = new HashMap<String, String>(3); globalVars.put("version", "$OO_CLOUD{version}"); Map<String, String> localVars = new HashMap<String, String>(3); localVars.put("groupId", "esb"); localVars.put("artifactId", "service"); CmsCI ci = new CmsCI(); ci.setCiId(140); ci.setCiName("processLocalVarDemo"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(2); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_LOCAL{groupId}:$OO_LOCAL{artifactId}:$OO_GLOBAL{version}"); String nameOfAttribute = "myArtifactGav"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, globalVars, localVars); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "esb:service:2.0"); } } } @Test(priority = 150) /** * test variable that user did not set, instead it is empty string "" this is NOT a bad reference */ public void processLocalVarBlankValue() { Map<String, String> cloudVars = new HashMap<String, String>(3); cloudVars.put("FOO", ""); CmsCI ci = new CmsCI(); ci.setCiId(150); ci.setCiName("processLocalVarBlankValue"); Map<String, CmsCIAttribute> attributes = new LinkedHashMap<String, CmsCIAttribute>(1); CmsCIAttribute attrL = new CmsCIAttribute(); attrL.setDjValue("$OO_CLOUD{FOO}"); String nameOfAttribute = "testingABlank"; attributes.put(nameOfAttribute, attrL); ci.setAttributes(attributes); Map<String, CmsCIAttribute> attributesBefore = ci.getAttributes(); for (Entry<String, CmsCIAttribute> e : attributesBefore.entrySet()) { System.out.println("*- b4 |" + e.getKey() + "->" + e.getValue().getDjValue()); } CmsUtil util = new CmsUtil(); dumpMaps(null, null, null); dumpCmsCIAttributes(ci); util.processAllVars(ci, cloudVars, null, null); dumpCmsCIAttributes(ci); for (Entry<String, CmsCIAttribute> a : ci.getAttributes().entrySet()) { String djKey = a.getKey(); String djAfter = a.getValue().getDjValue(); System.out.println("*after k>" + djKey + " v->" + djAfter); if (djKey.equals(nameOfAttribute)) { assertEquals(djAfter, "", "this is not a empty string as expected"); } } } @Test public void testErrorMessage() { String errorMessage = "CI tomcat, attribute: pre_shutdown_command has bad local var <DEPLOYCONTEXT> reference! value=null"; assertEquals( util.getErrorMessage("tomcat", "pre_shutdown_command", null, "DEPLOYCONTEXT"), errorMessage); } }
public class TestBase { protected EventFiringWebDriver driver; protected WebDriver dr; protected Properties locator; protected Properties conf; private Logger logger = Logger.getLogger(TestBase.class); public final String pathLocator = "src\\test\\resources\\configurations\\Locator.properties"; private DesiredCapabilities capabilities; public final String pathConf = "src\\test\\resources\\configurations\\Conf.properties"; protected String url; protected String br; protected String strTextValue = null; protected String originalWindowHandle; protected HomePage ObjTestHomePage; protected ResultPage ObjResultPage; public static final long PAGELOAD_TIMEOUT = 45L; public static final long IMPLICIT_WAIT = 20L; // will be called in before class public void initBeforeClass() { conf = readPropertiesFile(pathConf); url = conf.getProperty("url"); br = conf.getProperty("browser"); } // will be called in before method public void initBeforeMethod() { // initialize - all before methods logger.info("Starting init method"); locator = readPropertiesFile(pathLocator); // Launch webDriver dr = getWebDriver(br); driver = new EventFiringWebDriver(dr); // maximize driver.manage().window().maximize(); originalWindowHandle = driver.getWindowHandle(); // implicit wait, pageloadtimeout driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(PAGELOAD_TIMEOUT, TimeUnit.SECONDS); // navigate navigateTo(url); createObject(); } // close all existing opened browser public void closeAllBr() { try { driver.close(); driver.quit(); } catch (Throwable t) { logger.error("cannot close browser", t); } } public Properties readPropertiesFile(String path) { try { logger.info("loading properties file " + path); Properties prop = new Properties(); FileInputStream fis = new FileInputStream(path); prop.load(fis); return prop; } catch (Throwable t) { logger.error("File could not be loaded" + path, t); } return null; } // Load Browser public WebDriver getWebDriver(String br) { // make sure capabilities is not null logger.info("Starting WebDriver"); // Set the desired capabilities capabilities = setDesiredCapabilites(br); // To run test Cases on Firefox Browser. if (br.equalsIgnoreCase("firefox")) { dr = new FirefoxDriver(capabilities); return dr; } return null; } /** @param br purpose: set desiredCapanbilities */ public DesiredCapabilities setDesiredCapabilites(String browserCapability) { capabilities = new DesiredCapabilities(); switch (browserCapability) { case "firefox": capabilities.setBrowserName("firefox"); capabilities.setPlatform(Platform.ANY); break; default: try { throw new Throwable("no capalities matched"); } catch (Throwable e) { // TODO Auto-generated catch block logger.error("no capabilites found", e); } } return capabilities; } // createing object of all modules to use in test cases. Create object of every class. public void createObject() { ObjTestHomePage = new HomePage(driver, locator); ObjResultPage = new ResultPage(driver, locator); } // Nullifying all the variables. public void nullifyAllVariables() { ObjTestHomePage = null; ObjResultPage = null; } // ***************************************************** // basic method-type, click, double click, drag and drop // GetWebElement public WebElement getWebElement(By by) { try { logger.info("finding webelement by " + by); return driver.findElement(by); } catch (Throwable t) { logger.error("could not find webElement by " + by, t); } return null; } // ------------------------------------------------------- // Click Method. public void click(By by) { try { getWebElement(by).click(); } catch (Throwable t) { logger.error("cannot click by " + by, t); } } // selects by String value public void selectByValue(By by, String value) { try { new Select(getWebElement(by)).selectByValue(value); } catch (Throwable t) { logger.error("cannot select webelement by " + by, t); } } /*This Method can be used to clear the text field and send the keys after that*/ public void clearAndSendKeys(By by, String toType) { try { getWebElement(by).clear(); getWebElement(by).sendKeys(toType); } catch (Throwable t) { logger.error("cannot type to " + by, t); } } public String getTextValue(By by) { try { // String strTextValue= getWebElement(by).getText(); strTextValue = getWebElement(by).getText(); } catch (Throwable t) { logger.error("cannot type to " + by, t); } return strTextValue; } // This method can be used to navigate to specific url public void navigateTo(String url) { try { logger.info("navigating to url--" + url); driver.navigate().to(url); } catch (Throwable e) { logger.error("cannot navigate to url " + url, e); } } }
/** * Reported designed to render self-contained HTML top down view of a testing suite. * * @author Paul Mendelson * @since 5.2 * @version $Revision: 719 $ */ public class PowerEmailableReporter implements IReporter { private static final Logger L = Logger.getLogger(PowerEmailableReporter.class); // ~ Instance fields ------------------------------------------------------ private PrintWriter m_out; private int m_row; private Integer m_testIndex; private Set<Integer> testIds = new HashSet<Integer>(); private List<Integer> allRunTestIds = new ArrayList<Integer>(); private JavaDocBuilder builder = new JavaDocBuilder(); // ~ Methods -------------------------------------------------------------- /** Creates summary of the run */ public void generateReport(List<XmlSuite> xml, List<ISuite> suites, String outdir) { try { m_out = createWriter(outdir); } catch (IOException e) { L.error("output file", e); return; } ConfigReader cr = ConfigReader.getInstance(); builder.setEncoding(cr.getSrouceCodeEncoding()); builder.addSourceTree(new File(cr.getSourceCodeDir())); startHtml(m_out); generateSuiteSummaryReport(suites); testIds.clear(); generateMethodSummaryReport(suites); testIds.clear(); generateMethodDetailReport(suites); testIds.clear(); endHtml(m_out); m_out.flush(); m_out.close(); } protected PrintWriter createWriter(String outdir) throws IOException { new File(outdir).mkdirs(); return new PrintWriter( new BufferedWriter(new FileWriter(new File(outdir, "power-emailable-report.html")))); } /** Creates a table showing the highlights of each test method with links to the method details */ protected void generateMethodSummaryReport(List<ISuite> suites) { startResultSummaryTable("methodOverview"); int testIndex = 1; for (ISuite suite : suites) { if (suites.size() > 1) { titleRow(suite.getName(), 5); } Map<String, ISuiteResult> r = suite.getResults(); for (ISuiteResult r2 : r.values()) { ITestContext testContext = r2.getTestContext(); String testName = testContext.getName(); m_testIndex = testIndex; resultSummary( suite, testContext.getSkippedConfigurations(), testName, "skipped", " (configuration methods)"); resultSummary(suite, testContext.getSkippedTests(), testName, "skipped", ""); resultSummary( suite, testContext.getFailedConfigurations(), testName, "failed", " (configuration methods)"); resultSummary(suite, testContext.getFailedTests(), testName, "failed", ""); resultSummary(suite, testContext.getPassedTests(), testName, "passed", ""); testIndex++; } } m_out.println("</table>"); } /** Creates a section showing known results for each method */ protected void generateMethodDetailReport(List<ISuite> suites) { for (ISuite suite : suites) { Map<String, ISuiteResult> r = suite.getResults(); for (ISuiteResult r2 : r.values()) { ITestContext testContext = r2.getTestContext(); if (r.values().size() > 0) { m_out.println("<h1>" + testContext.getName() + "</h1>"); } resultDetail(testContext.getFailedConfigurations()); resultDetail(testContext.getFailedTests()); resultDetail(testContext.getSkippedConfigurations()); resultDetail(testContext.getSkippedTests()); resultDetail(testContext.getPassedTests()); } } } /** @param tests */ private void resultSummary( ISuite suite, IResultMap tests, String testname, String style, String details) { if (tests.getAllResults().size() > 0) { StringBuffer buff = new StringBuffer(); String lastClassName = ""; int mq = 0; int cq = 0; Map<String, Integer> methods = new HashMap<String, Integer>(); Set<String> setMethods = new HashSet<String>(); for (ITestNGMethod method : getMethodSet(tests, suite)) { m_row += 1; ITestClass testClass = method.getTestClass(); String className = testClass.getName(); if (mq == 0) { String id = (m_testIndex == null ? null : "t" + Integer.toString(m_testIndex)); titleRow(testname + " — " + style + details, 5, id); m_testIndex = null; } if (!className.equalsIgnoreCase(lastClassName)) { if (mq > 0) { cq += 1; m_out.print("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td"); if (mq > 1) { m_out.print(" rowspan=\"" + mq + "\""); } m_out.println(">" + lastClassName + "</td>" + buff); } mq = 0; buff.setLength(0); lastClassName = className; } Set<ITestResult> resultSet = tests.getResults(method); long end = Long.MIN_VALUE; long start = Long.MAX_VALUE; for (ITestResult testResult : tests.getResults(method)) { if (testResult.getEndMillis() > end) { end = testResult.getEndMillis(); } if (testResult.getStartMillis() < start) { start = testResult.getStartMillis(); } } mq += 1; if (mq > 1) { buff.append("<tr class=\"" + style + (cq % 2 == 0 ? "odd" : "even") + "\">"); } String description = method.getDescription(); String testInstanceName = resultSet.toArray(new ITestResult[] {})[0].getTestName(); // Calculate each test run times, the result shown in the html // report. ITestResult[] results = resultSet.toArray(new ITestResult[] {}); String methodName = method.getMethodName(); if (setMethods.contains(methodName)) { methods.put(methodName, methods.get(methodName) + 1); } else { setMethods.add(methodName); methods.put(methodName, 0); } String parameterString = ""; int count = 0; ITestResult result = null; if (results.length > methods.get(methodName)) { result = results[methods.get(methodName)]; int testId = getId(result); for (Integer id : allRunTestIds) { if (id.intValue() == testId) count++; } Object[] parameters = result.getParameters(); boolean hasParameters = parameters != null && parameters.length > 0; if (hasParameters) { for (Object p : parameters) { parameterString = parameterString + Utils.escapeHtml(p.toString()) + " "; } } } int methodId = method.getTestClass().getName().hashCode(); methodId = methodId + method.getMethodName().hashCode(); if (result != null) methodId = methodId + (result.getParameters() != null ? Arrays.hashCode(result.getParameters()) : 0); buff.append( "<td><a href=\"#m" + methodId + "\">" + qualifiedName(method) + " " + (description != null && description.length() > 0 ? "(\"" + description + "\")" : "") + "</a>" + (null == testInstanceName ? "" : "<br>(" + testInstanceName + ")") + "</td><td>" + this.getAuthors(className, method) + "</td><td class=\"numi\">" + resultSet.size() + "</td>" + "<td>" + (count == 0 ? "" : count) + "</td>" + "<td>" + parameterString + "</td>" + "<td>" + start + "</td>" + "<td class=\"numi\">" + (end - start) + "</td>" + "</tr>"); } if (mq > 0) { cq += 1; m_out.print("<tr class=\"" + style + (cq % 2 == 0 ? "even" : "odd") + "\">" + "<td"); if (mq > 1) { m_out.print(" rowspan=\"" + mq + "\""); } m_out.println(">" + lastClassName + "</td>" + buff); } } } /** Starts and defines columns result summary table */ private void startResultSummaryTable(String style) { tableStart(style, "summary"); m_out.println( "<tr><th>Class</th><th>Method</th><th>Authors</th><th># of<br/>Scenarios</th><th>Running Counts</th>" + "<th>Parameters</th><th>Start</th><th>Time<br/>(ms)</th></tr>"); m_row = 0; } private String qualifiedName(ITestNGMethod method) { StringBuilder addon = new StringBuilder(); String[] groups = method.getGroups(); int length = groups.length; if (length > 0 && !"basic".equalsIgnoreCase(groups[0])) { addon.append("("); for (int i = 0; i < length; i++) { if (i > 0) { addon.append(", "); } addon.append(groups[i]); } addon.append(")"); } return "<b>" + method.getMethodName() + "</b> " + addon; } private void resultDetail(IResultMap tests) { for (ITestResult result : tests.getAllResults()) { ITestNGMethod method = result.getMethod(); int methodId = getId(result); String cname = method.getTestClass().getName(); m_out.println( "<h2 id=\"m" + methodId + "\" name=\"m" + methodId + "\" >" + cname + ":" + method.getMethodName() + "</h2>"); Set<ITestResult> resultSet = tests.getResults(method); generateForResult(result, method, resultSet.size()); m_out.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>"); } } private void generateForResult(ITestResult ans, ITestNGMethod method, int resultSetSize) { Object[] parameters = ans.getParameters(); boolean hasParameters = parameters != null && parameters.length > 0; if (hasParameters) { tableStart("result", null); m_out.print("<tr class=\"param\">"); for (int x = 1; x <= parameters.length; x++) { m_out.print("<th>Parameter #" + x + "</th>"); } m_out.println("</tr>"); m_out.print("<tr class=\"param stripe\">"); for (Object p : parameters) { m_out.println("<td>" + Utils.escapeHtml(p.toString()) + "</td>"); } m_out.println("</tr>"); } List<String> msgs = Reporter.getOutput(ans); boolean hasReporterOutput = msgs.size() > 0; Throwable exception = ans.getThrowable(); boolean hasThrowable = exception != null; if (hasReporterOutput || hasThrowable) { if (hasParameters) { m_out.print("<tr><td"); if (parameters.length > 1) { m_out.print(" colspan=\"" + parameters.length + "\""); } m_out.println(">"); } else { m_out.println("<div>"); } if (hasReporterOutput) { if (hasThrowable) { m_out.println("<h3>Test Messages</h3>"); } for (String line : msgs) { m_out.println(line + "<br/>"); } } if (hasThrowable) { boolean wantsMinimalOutput = ans.getStatus() == ITestResult.SUCCESS; if (hasReporterOutput) { m_out.println("<h3>" + (wantsMinimalOutput ? "Expected Exception" : "Failure") + "</h3>"); } generateExceptionReport(exception, method); } if (hasParameters) { m_out.println("</td></tr>"); } else { m_out.println("</div>"); } } if (hasParameters) { m_out.println("</table>"); } } protected void generateExceptionReport(Throwable exception, ITestNGMethod method) { m_out.print("<div class=\"stacktrace\">"); m_out.print(Utils.stackTrace(exception, true)[0]); m_out.println("</div>"); } /** * Since the methods will be sorted chronologically, we want to return the ITestNGMethod from the * invoked methods. */ private Collection<ITestNGMethod> getMethodSet(IResultMap tests, ISuite suite) { List<IInvokedMethod> r = Lists.newArrayList(); List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods(); // Eliminate the repeat retry methods for (IInvokedMethod im : invokedMethods) { if (tests.getAllMethods().contains(im.getTestMethod())) { int testId = getId(im.getTestResult()); if (!testIds.contains(testId)) { testIds.add(testId); r.add(im); } } } Arrays.sort(r.toArray(new IInvokedMethod[r.size()]), new TestSorter()); List<ITestNGMethod> result = Lists.newArrayList(); // Add all the invoked methods for (IInvokedMethod m : r) { result.add(m.getTestMethod()); } // Add all the methods that weren't invoked (e.g. skipped) that we // haven't added yet // for (ITestNGMethod m : tests.getAllMethods()) { // if (!result.contains(m)) { // result.add(m); // } // } for (ITestResult allResult : tests.getAllResults()) { int testId = getId(allResult); if (!testIds.contains(testId)) { result.add(allResult.getMethod()); } } return result; } public void generateSuiteSummaryReport(List<ISuite> suites) { tableStart("testOverview", null); m_out.print("<tr>"); tableColumnStart("Test"); tableColumnStart("Methods<br/>Passed"); tableColumnStart("Scenarios<br/>Passed"); tableColumnStart("# skipped"); tableColumnStart("# failed"); tableColumnStart("Total<br/>Time"); tableColumnStart("Included<br/>Groups"); tableColumnStart("Excluded<br/>Groups"); m_out.println("</tr>"); NumberFormat formatter = new DecimalFormat("#,##0.0"); int qty_tests = 0; int qty_pass_m = 0; int qty_pass_s = 0; int qty_skip = 0; int qty_fail = 0; long time_start = Long.MAX_VALUE; long time_end = Long.MIN_VALUE; m_testIndex = 1; for (ISuite suite : suites) { if (suites.size() > 1) { titleRow(suite.getName(), 8); } Map<String, ISuiteResult> tests = suite.getResults(); for (ISuiteResult r : tests.values()) { qty_tests += 1; ITestContext overview = r.getTestContext(); startSummaryRow(overview.getName()); getAllTestIds(overview, suite); int q = getMethodSet(overview.getPassedTests(), suite).size(); qty_pass_m += q; summaryCell(q, Integer.MAX_VALUE); q = overview.getPassedTests().size(); qty_pass_s += q; summaryCell(q, Integer.MAX_VALUE); q = getMethodSet(overview.getSkippedTests(), suite).size(); qty_skip += q; summaryCell(q, 0); q = getMethodSet(overview.getFailedTests(), suite).size(); qty_fail += q; summaryCell(q, 0); time_start = Math.min(overview.getStartDate().getTime(), time_start); time_end = Math.max(overview.getEndDate().getTime(), time_end); summaryCell( formatter.format( (overview.getEndDate().getTime() - overview.getStartDate().getTime()) / 1000.) + " seconds", true); summaryCell(overview.getIncludedGroups()); summaryCell(overview.getExcludedGroups()); m_out.println("</tr>"); m_testIndex++; } } if (qty_tests > 1) { m_out.println("<tr class=\"total\"><td>Total</td>"); summaryCell(qty_pass_m, Integer.MAX_VALUE); summaryCell(qty_pass_s, Integer.MAX_VALUE); summaryCell(qty_skip, 0); summaryCell(qty_fail, 0); summaryCell(formatter.format((time_end - time_start) / 1000.) + " seconds", true); m_out.println("<td colspan=\"2\"> </td></tr>"); } m_out.println("</table>"); } private void summaryCell(String[] val) { StringBuffer b = new StringBuffer(); for (String v : val) { b.append(v + " "); } summaryCell(b.toString(), true); } private void summaryCell(String v, boolean isgood) { m_out.print("<td class=\"numi" + (isgood ? "" : "_attn") + "\">" + v + "</td>"); } private void startSummaryRow(String label) { m_row += 1; m_out.print( "<tr" + (m_row % 2 == 0 ? " class=\"stripe\"" : "") + "><td style=\"text-align:left;padding-right:2em\"><a href=\"#t" + m_testIndex + "\">" + label + "</a>" + "</td>"); } private void summaryCell(int v, int maxexpected) { summaryCell(String.valueOf(v), v <= maxexpected); } private void tableStart(String cssclass, String id) { m_out.println( "<table cellspacing=\"0\" cellpadding=\"0\"" + (cssclass != null ? " class=\"" + cssclass + "\"" : " style=\"padding-bottom:2em\"") + (id != null ? " id=\"" + id + "\"" : "") + ">"); m_row = 0; } private void tableColumnStart(String label) { m_out.print("<th>" + label + "</th>"); } private void titleRow(String label, int cq) { titleRow(label, cq, null); } private void titleRow(String label, int cq, String id) { m_out.print("<tr"); if (id != null) { m_out.print(" id=\"" + id + "\""); } m_out.println("><th colspan=\"" + cq + "\">" + label + "</th></tr>"); m_row = 0; } /** Starts HTML stream */ protected void startHtml(PrintWriter out) { out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); out.println("<head>"); out.println("<title>TestNG Report</title>"); out.println("<style type=\"text/css\">"); out.println("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}"); out.println("td,th {border:1px solid #009;padding:.25em .5em}"); out.println(".result th {vertical-align:bottom}"); out.println(".param th {padding-left:1em;padding-right:1em}"); out.println(".param td {padding-left:.5em;padding-right:2em}"); out.println(".stripe td,.stripe th {background-color: #E6EBF9}"); out.println(".numi,.numi_attn {text-align:right}"); out.println(".total td {font-weight:bold}"); out.println(".passedodd td {background-color: #0A0}"); out.println(".passedeven td {background-color: #3F3}"); out.println(".skippedodd td {background-color: #CCC}"); out.println(".skippedodd td {background-color: #DDD}"); out.println(".failedodd td,.numi_attn {background-color: #F33}"); out.println(".failedeven td,.stripe .numi_attn {background-color: #D00}"); out.println(".stacktrace {white-space:pre;font-family:monospace}"); out.println(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}"); out.println("</style>"); out.println("</head>"); out.println("<body>"); } /** Finishes HTML stream */ protected void endHtml(PrintWriter out) { out.println("</body></html>"); } // ~ Inner Classes -------------------------------------------------------- /** Arranges methods by classname and method name */ private class TestSorter implements Comparator<IInvokedMethod> { // ~ Methods // ------------------------------------------------------------- /** Arranges methods by classname and method name */ public int compare(IInvokedMethod o1, IInvokedMethod o2) { // System.out.println("Comparing " + o1.getMethodName() + " " + // o1.getDate() // + " and " + o2.getMethodName() + " " + o2.getDate()); return (int) (o1.getDate() - o2.getDate()); // int r = ((T) o1).getTestClass().getName().compareTo(((T) // o2).getTestClass().getName()); // if (r == 0) { // r = ((T) o1).getMethodName().compareTo(((T) o2).getMethodName()); // } // return r; } } // ~ JavaDoc-specific Methods // -------------------------------------------------------- /** * Get ITestNGMethod author(s) string, or class author(s) if no method author is present. Default * return value is "unknown". * * @param className * @param method * @return * @author hzjingcheng */ private String getAuthors(String className, ITestNGMethod method) { JavaClass cls = builder.getClassByName(className); DocletTag[] authors = cls.getTagsByName("author"); // get class authors as default author name String allAuthors = ""; if (authors.length == 0) { allAuthors = "unknown"; } else { for (DocletTag author : authors) { allAuthors += author.getValue() + " "; } } // get method author name JavaMethod[] mtds = cls.getMethods(); for (JavaMethod mtd : mtds) { if (mtd.getName().equals(method.getMethodName())) { authors = mtd.getTagsByName("author"); if (authors.length != 0) { allAuthors = ""; for (DocletTag author : authors) { allAuthors += author.getValue() + " "; } } break; } } return allAuthors.trim(); } /** * Get comment string of Java class. * * @param className * @return * @author hzjingcheng */ @SuppressWarnings("unused") private String getClassComment(String className) { JavaClass cls = builder.getClassByName(className); return cls.getComment(); } /** * Get ITestResult id by class + method + parameters hash code. * * @param result * @return * @author kevinkong */ private int getId(ITestResult result) { int id = result.getTestClass().getName().hashCode(); id = id + result.getMethod().getMethodName().hashCode(); id = id + (result.getParameters() != null ? Arrays.hashCode(result.getParameters()) : 0); return id; } /** * Get All tests id by class + method + parameters hash code. * * @param context * @param suite * @author kevinkong */ private void getAllTestIds(ITestContext context, ISuite suite) { IResultMap passTests = context.getPassedTests(); IResultMap failTests = context.getFailedTests(); List<IInvokedMethod> invokedMethods = suite.getAllInvokedMethods(); for (IInvokedMethod im : invokedMethods) { if (passTests.getAllMethods().contains(im.getTestMethod()) || failTests.getAllMethods().contains(im.getTestMethod())) { int testId = getId(im.getTestResult()); // m_out.println("ALLtestid=" + testId); allRunTestIds.add(testId); } } } }