How to rename the file before uploading in selenium - java

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"));

Related

How to add files inside temporary directory in JUnit

I found two ways to create temporary directories in JUnit.
Way 1:
#Rule
public TemporaryFolder tempDirectory = new TemporaryFolder();
#Test
public void testTempDirectory() throws Exception {
tempDirectory.newFile("test.txt");
tempDirectory.newFolder("myDirectory");
// how do I add files to myDirectory?
}
Way 2:
#Test
public void testTempDirectory() throws Exception {
File myFile = File.createTempFile("abc", "txt");
File myDirectory = Files.createTempDir();
// how do I add files to myDirectory?
}
As the comment above mentions, I have a requirement where I want to add some temporary files in these temporary directories. Run my test against this structure and finally delete everything on exit.
How do I do that?
You can do it the same way you do it for real folders.
#Rule
public TemporaryFolder rootFolder = new TemporaryFolder();
#Test
public void shouldCreateChildFile() throws Exception {
File myFolder = rootFolder.newFolder("my-folder");
File myFile = new File(myFolder, "my-file.txt");
}
Using new File(subFolderOfTemporaryFolder, "fileName") did not work for me. Calling subFolder.list() returned an empty array. This is how I made it work:
#Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
#Test
public void createFileInSubFolderOfTemporaryFolder() throws IOException {
String subFolderName = "subFolder";
File subFolder = temporaryFolder.newFolder(subFolderName);
temporaryFolder.newFile(subFolderName + File.separator + "fileName1");
String[] actual = subFolder.list();
assertFalse(actual.length == 0);
}
Using TemporaryFolder creates a directory with a common root. Once you have created a folder, you can then create a file by specifying the directory structure and the final filename as the name.
#Rule
public TemporaryFolder rootFolder = new TemporaryFolder();
#Test
public void shouldCreateChildFile() throws Exception {
File myFolder = rootFolder.newFolder("my-folder");
File myFileInMyFolder = rootFolder.newFile("/my-folder/my-file.txt");
}
You can create child directories in the same way.
There two ways to delete temp directory or temp file.Fist,delete the dirctory or file manually use file.delete() method,Second,delete the temp directory or file when program exis user file.deleteOnExist().
You can try this,I print the path to console,you can to check realy delte or not,I test on windows7 system.
File myDirectory = Files.createTempDir();
File tmpFile = new File(myDirectory.getAbsolutePath() + File.separator + "test.txt");
FileUtils.writeStringToFile(tmpFile, "HelloWorld", "UTF-8");
System.out.println(myDirectory.getAbsolutePath());
// clean
tmpFile.delete();
myDirectory.deleteOnExit();

Issue: Shutterbug Screenshot create a new folder for each screenshot instead of keeping them in 1 folder

I have below code to capture the screenshot with Shutterbug. but it creates the folder and store the screenshot in the folder. Can someone help me to identify the issue? Ideally, i would like to save all the screenshot in one folder.
public class CaptureScreenshot {
public static void Screenshot(WebDriver driver,String screenshotName) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy-hhmmss");
Date date = new Date();
String screenshotNameFormat = screenshotName + " "+ formatter.format(date);
Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS,500,true).withName(screenshotNameFormat).save("./ScreenShots/"+screenshotNameFormat+".png");
}
}
The github page on selenium-shutterbug indicates that save() would only take the directory, not the filename as well:
Shutterbug.shootPage(driver)
...
.withName("home_page")
...
.save("C:\\testing\\screenshots\\");
So in your case it should be
Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS,500,true).withName(screenshotNameFormat).save("./ScreenShots/");

how to create custom reports in testng

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.

How to call a method from property file using Java and Selenium WebDriver?

Currently Working on Selenium WebDriver and code I'm writing in Java.
I have created a MasterScript called Master.java which is the main script and it looks like this:
package test;
import org.openqa.selenium.WebDriver;
public class MasterScript {
public static void main(String[] args) throws Exception {
//*****************************************************
// Calling Methods
//*****************************************************
LoginOneReports utilObj = new LoginOneReports ();
WebDriver driver;
driver=utilObj.setUp();
if(utilObj.Login()){
System.out.println("Login sucessfully completed");
} else {
System.out.println("Login failed");
System.exit(0);
}
NewPR utilObj1 = new NewPR(driver); // instead of calling one PR it need to pick from the property file and it need to select the KPI in UI
if(utilObj1.test()){
System.out.println("NewPR KPI page has opened");
} else {
System.out.println("NewPR KPI not able to open");
}
FilterSection utilObj2 =new FilterSection(driver);
utilObj2.FilterMatching();
}
}
Put this dynamic values in the property file where each and every time it need to go to the property file and fetch the value, based on the value the related java file need to called.
Hi Just for example we will call the property file as setup.txt
say for example you have a url in ur setup file as "internal.url=https://google.com"
create a constructor
public MasterScript() throws IO Exception
{
setup_details();
}
public void setup_details()throws IOException{
FileInputStream inStream;
inStream = new FileInputStream(new File("Setupfiles\\setup.txt"));
Properties prop = new Properties();
prop.load(inStream);
internal_url=prop.getProperty("internal.url");
}
IN THE SETUP FILE*
internal.url=https://google.com
name the txt file as setup.txt
Now while using that in the main class u can just use "driver.get(internal_url);"
Hope This helps you...

Deleting File and Directory in JUnit

I'm writing a test for a method that creates a file in a directory. Here's what my JUnit test looks like:
#Before
public void setUp(){
objectUnderTest = new ClassUnderTest();
//assign another directory path for testing using powermock
WhiteBox.setInternalState(objectUnderTest, "dirPathField", mockDirPathObject);
nameOfFile = "name.txt";
textToWrite = "some text";
}
#Test
public void shouldCreateAFile(){
//create file and write test
objectUnderTest.createFile(nameOfFile, textToWrite);
/* this method creates the file in mockPathObject and performs
FileWriter.write(text);
FileWriter.close();
*/
File expect = new File(mockPathObject + "\\" + nameOfFile);
assertTrue(expect.exist());
//assert if text is in the file -> it will not be called if first assert fails
}
#After
public void tearDown(){
File destroyFile = new File(mockPathObject + "\\" + nameOfFile);
File destroyDir = new File(mockPathObject);
//here's my problem
destroyFile.delete(); //why is this returning false?
destroyDir.delete(); //will also return false since file was not deleted above
}
I was able to delete the File using deleteOnExit() but I will not be able to delete the directory using delete or deleteOnExit. I will also perform other test for other scenarios in this test script so I don't want to use deleteOnExit.
I don't know why I cannot delete it in JUnit test script while I can delete a file created and modified by FileWriter in runtime when the code is not a JUnit test. I also tried performing an infiniteLoop after the test method and delete the file manually but it tells me that other program is still using the file though I'm able to modify its content.
Hope somebody can suggest a way to delete the files and directories created during the tests. Thanks :D
For more clarity, the method I test looks like this Unit testing method that invokes FileWriter
Edit:Here is the method to test
public void createFile(String fileName, String text){
//SOME_PATH is a static string which is a field of the class
File dir = new File(SOME_PATH); //I modified SOME_PATH using whitebox for testing
if(!dir.exists()){
booelan createDir = dir.mkdirs();
if(!createDir){
sysout("cannot make dir");
return;
}
}
try{
FileWriter fileWrite = new FileWriter(dir.getAbsolutePath() + "/" + fileName, true);
fileWrite.write(text);
fileWrite.close();
}
catch(Exception e){
e.printStackTrace();
}
}
I cannot modify this method as other developers created it. I was just instructed to create unit tests for test automation. Thanks.
Use the #Rule annotation and the TemporaryFolder classfor the folder that you need to delete.
http://kentbeck.github.com/junit/javadoc/4.10/org/junit/Rule.html (404 not found)
Update example of usage by http://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html:
public static class HasTempFolder {
#Rule
public TemporaryFolder folder= new TemporaryFolder();
#Test
public void testUsingTempFolder() throws IOException {
File createdFile= folder.newFile("myfile.txt");
File createdFolder= folder.newFolder("subfolder");
// ...
}
}
This is how I usually clean up files:
#AfterClass
public static void clean() {
File dir = new File(DIR_PATH);
for (File file:dir.listFiles()) {
file.delete();
}
dir.delete();
}
Your directory must be empty in order to delete it, make sure no other test methods are creating more files there.
Ensure you are closing the FileWriter instance in a finally block.
Ensure that the method objectUnderTest.createFile(nameOfFile, textToWrite) actually closes any opened streams?
I think the best approche is te delete after JVM exit :
Path tmp = Files.createTempDirectory(null);
tmp.toFile().deleteOnExit();

Categories

Resources