I have the following Java code:
public class Login {
String Login_Status = null;
String Login_Message = null;
#Test
#Parameters({"USERNAME","PASSWORD"})
public void Execute(String UserName, String Password) throws IOException {
try {
Config.driver.findElement(By.linkText("Log in")).click();
Config.driver.findElement(By.id("user_login")).sendKeys(UserName);
Config.driver.findElement(By.id("user_pass")).sendKeys(Password);
Config.driver.findElement(By.id("wp-submit")).click();
// perform validation here
boolean expvalue = Config.driver.findElement(By.xpath("//a[#rel='home']")).isDisplayed();
if (expvalue) {
Login_Status = "PASS";
Login_Message="Login Successfull for user:" + UserName + ",password:" + Password + ",\n EXPECTED: rtMedia Demo Site LINK SHOULD BE PRESENT ON THE HOME PAGE OF rtMedia ACTUAL: rtMedia LINK is PRESENT ON THE HOME PAGE OF rtMedia. DETAILS:NA";
}
} catch(Exception generalException) {
Login_Status = "FAIL";
Login_Message = "Login UnSuccessfull for user:" + UserName + ",password:" + Password + ",\n EXPECTED: rtMedia Demo Site LINK SHOULD BE PRESENT ON THE HOME PAGE OF rtMedia ACTUAL: rtMedia LINK is NOT PRESENT ON THE HOME PAGE OF rtMedia. DETAILS:Exception Occurred:"+generalException.getLocalizedMessage();
// File scrFile = ((TakesScreenshot) Config.driver).getScreenshotAs(OutputType.FILE);
// FileUtils.copyFile(scrFile, new File("C:\\Users\\Public\\Pictures\\failure.png"));
} finally {
Assert.assertTrue(Login_Status.equalsIgnoreCase("PASS"), Login_Message);
}
}
}
I wrote the above Java code for login functionality and now I want to create reports for whatever the result will be (pass or fail) and it should be stored in folder? I have no idea about the generating the reports and also I found the reports are automatically generated by TestNG itself but when we run another test it gets overwritten, that will not help for me. Any help?
There are quite a few ways you can achieve this
If you're using XML report then you can implement IReporter and create a listener. You have to override a method called generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) and you can have your own logic to save the output in a different folder everytime you run the test case.
There is an attribute in testNG called fileFragmentationLevel if you set it to 3 I think your report will not be overwritten. It's in XML reporter class
You can create a listener that will extend TestListenerAdapter and override onStart(ITestContext testContext) method to back up your testoutput folder everytime. But I don't prefer this method.
I prefer #1.
Related
I am trying to upload same file in multiple tests and under every test the file name should be unique. So the file name should be renamed automaticaly before uplaoding. I have provided the code snippet that i have used for uplaoding below.
//Constants.java
public static final String EXCEL_FILE = System.getProperty("user.dir") + "/src/main/resources /TestData/a.xlxs"
//page class //HomePage.java
public void uploadCSVFileSendKeys(String filePath){
uploadFile.sendKeys(filePath);
}
//test class
#Test(priority =1 )
public void VerifySuccessfulFileUpload(){
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
HomePage homePage = PageFactory.initElements(driver, HomePage.class);
loginPage.login(Constants.userName, Constants.password);
homePage.uploadCSVFileSendKeys(Constants.EXCEL_FILE);
homePage.uploadFile();
}
I tried adding "filepath + System.currentTimeMillis()", But provided an error as "File not found". Tried adding date and time to the file path, same error was thrown.
Please provide a solution for this.
You can duplicate the original file and upload it. Once the required code is being executed, if you wish to delete then delete the file.
public String uploadCSVFileSendKeys(String filePath) {
File originalFile = new File(filePath);
File renamedFile = new File(System.getProperty("user.dir") + "/src/main/resources"
+ RandomStringUtils.randomAlphanumeric(24) + ".xlxs");
FileUtils.copyFile(originalFile, renamedFile);
uploadFile.sendKeys(renamedFile);
return renamedFile.getAbsolutePath();
}
To delete File
FileUtils.delete(new File("duplicateFileLocation"));
I am facing a problem with registration and login flow where it is required to generate an email and get token for verification. I need a service which allows user to generate n numbers of disposable emails with email data access that can self-destructs max 24 hours. Could anyone please share the service code to use in selenium java automation?
The QA teams leave such tasks for manual testing instead of writing automation tests for these scenarios. \
But, all communication from the email can be automated by the disposable email service. This article will describe how to use this service within the automation suite using Nightwatch.js (Node).
Registration and Login automation
You can use this code as well to automate such things:
2. Write down the logic of getEmail in common-function class and add dependencies in pom.xml file :
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
We will use Unirest for handling the Mail7 API code. it is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.
Create a mail7.java file with below code
import org.apcahe.commons.lang3.RandomStringUtils;
public class mail7{
private static final String EMAIL-DOMAIN = ‘mail.io’;
private static final String EMAIL_APIKEY = ‘mail7_api_key’;
private static final String EMAIL_APISecret = ‘mail7_api_secret’;
private String emailid;
public usernameGenerator(){
String username = RandomStringUtils.randomAlphanumeric(8).toLowerCase();
System.out. println(“Random Username is ” + username);
return username;
}
public getInbox(String username){
HttpResponse <String> httpResponse = Unirest.get(“"https://api.mail7.io/inbox?apikey=" + EMAIL_APIKEY + "&apisecret=" + EMAIL_APISecret + "&to=" + username”)
.asString();
System.out.println( httpResponse.getHeaders().get("Content-Type"));
System.out.println(httpResponse.getBody());
return httpResponse.getBody();
}
3. Create a class file for Test Script of Register and Login event :
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class TestEmail throws IOException, UnirestException
{
public static void main(String[] args) {
//create a Selenium WebDriver instance
System.setProperty("webdriver.gecko.driver","dir_path\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//launch the Firefox browser and navigate to the website
driver.get(“YOUR_TEST_URL");
//puts an implicit wait for 10 seconds before throwing exceptions
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//locate the email field
WebElement email = driver.findElement(By.xpath("//input[#type='email']"));
// create a random email address
String username = usernameGenerator();
String emailID = username.concat(“#”+EMAIL_DOMIAN);
//set the field's value
email.sendKeys(emailID);
//locate the password field
WebElement password = driver.findElement(By.xpath("//input[#type='password']"));
//set the password's value
password.sendKeys("password");
//locate and click the submit button
driver.findElement(By.xpath("//input[#type='submit']")).click();
//check if the mail has been received or not
String response = getInbo(username );
if(response.isEmpty()) {
System.out.println("Test not passed");
}else {
System.out.println("Test passed");
}
//close the Firefox browser.
driver.close();
}
}
}
}
I am using IReporter TestNG interface in Selenium, but how to capture screenshot and add in Extent Report for failed test-case ?
Please help me to find the solution.
Below is the code for attaching failed test case screenshots to the Extent Report.
MyReporterClass implements IReporter interface: It iterates over the test cases in the test suite and saves the status for each test case.
public class MyReporterClass implements IReporter {
#Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
//Iterating over each suite included in the test
for (ISuite suite : suites) {
//Following code gets the suite name
String suiteName = suite.getName();
//Getting the results for the said suite
Map<String, ISuiteResult> suiteResults = suite.getResults();
for (ISuiteResult sr : suiteResults.values()) {
ITestContext tc = sr.getTestContext();
System.out.println("Passed tests for suite '" + suiteName +
"' is:" + tc.getPassedTests().getAllResults().size());
System.out.println("Failed tests for suite '" + suiteName +
"' is:" + tc.getFailedTests().getAllResults().size());
System.out.println("Skipped tests for suite '" + suiteName +
"' is:" + tc.getSkippedTests().getAllResults().size());
}
}
}
}
getScreenshot() method: To capture the screenshot and return the destination path for the screenshot.
public class ExtentReportsClass{
public static String getScreenshot(WebDriver driver, String screenshotName) throws Exception {
//below line is just to append the date format with the screenshot name to avoid duplicate names
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
//after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/"+screenshotName+dateName+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
//Returns the captured file path
return destination;
}
}
#AfterMethod
public void getResult(ItestResult result): It is executed after each test case execution and attaches the failed test case screenshot to Extent report.
#AfterMethod
public void getResult(ITestResult result) throws IOException{
if(result.getStatus() == ITestResult.FAILURE){
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getName());
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getThrowable());
//To capture screenshot path and store the path of the screenshot in the string "screenshotPath"
String screenshotPath = ExtentReportsClass.getScreenshot(driver, result.getName());
//To add it in the extent report
logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
testng.xml file : Include the below listener tag in the xml file .
<listeners>
<listener class-name="packagename.MyReporterClass" />
</listeners>
I'm creating an application in Java and using jGit. As part of this I need to authenticate an user. I want to output if the user is existing or not. Currently I get an exception as user is not authorized. Below is my code.
import java.io.File;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
public class AuthenticateanUser {
public static void main(String[] args) throws Exception {
final String REMOTE_URL = "https://myRepo.git";
// prepare a new folder for the cloned repository
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
// then clone
try (Git result = Git.cloneRepository().setURI(REMOTE_URL)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider("myId", "myPwd"))
.setDirectory(localPath).call()) {
System.out.println("Having repository: " + result.status());
}
}
}
when I run my above code, If I give correct credentials, I get the output as
Having repository:XXXXX
if I give wrong credentials I get error as
Exception in thread "main" org.eclipse.jgit.api.errors.TransportException: https://myRepo.git: not authorized
Instead of this I want to print, Invalid credentials.
please let me know where am I going wrong and how can I fix this.
Thanks
You go:
try (Git result = Git.cloneRepository().setURI(REMOTE_URL) {
...
} catch (TransportException te) {
System.out.println("Invalid credentials");
}
for example.
You should not tell the user if the account exists or not. As in: if you tell that an attacker, he can conclude that he already got a valid username.
My framework consists of TestNG + Cucumber +Jenkins , I'm running the job using bat file configuration in jenkins.
My doubt is , I have a class file to launch the browser and I pass string value to if loop saying ,
if string equals "chrome" then launch the Chrome browser and soon.
Is there a way to pass the chrome value from jenkins into class file ?
example :
public class launch(){
public static String browser ="chrome"
public void LaunchBrowser() throws Exception{
if (browser.equalsIgnoreCase("chrome"))
{
launch chrome driver
}
}
Now i would like to pass the static string value from jenkins ,
Help is appreciated.
Thanks in advance.
You can do something like below
public class Launch {
//You would be passing the Browser flavor using -Dbrowser
//If you don't pass any browser name, then the below logic defaults to chrome
private static String browser =System.getProperty("browser", "chrome");
public void LaunchBrowser() throws Exception {
if (browser.equalsIgnoreCase("chrome")) {
//launch chrome driver
}
}
}