DownloadTest

This commit is contained in:
Guillem Hernandez Sola
2026-06-12 12:42:46 +02:00
parent 6ac43f79ed
commit fb07c83fe3
2 changed files with 96 additions and 35 deletions

View File

@@ -5,7 +5,6 @@ import java.time.Duration;
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxDriver;
@@ -23,6 +22,7 @@ public class BaseTest {
String browser = System.getProperty("browser"); String browser = System.getProperty("browser");
if (browser != null && browser.equalsIgnoreCase("firefox")) { if (browser != null && browser.equalsIgnoreCase("firefox")) {
FirefoxOptions options = new FirefoxOptions(); FirefoxOptions options = new FirefoxOptions();
options.addArguments("--start-maximized");
/* Activar si fa falta el driver en el PATH del sistema /* Activar si fa falta el driver en el PATH del sistema
System.setProperty("webdriver.gecko.driver", System.setProperty("webdriver.gecko.driver",
"src" + File.separator + "test" "src" + File.separator + "test"
@@ -42,15 +42,15 @@ public class BaseTest {
driver = new SafariDriver(); driver = new SafariDriver();
} }
else { else {
ChromeOptions options = new ChromeOptions();
/* Activar si fa falta el driver en el PATH del sistema /* Activar si fa falta el driver en el PATH del sistema
System.setProperty("webdriver.chrome.driver", "src" System.setProperty("webdriver.chrome.driver", "src"
+ File.separator + File.separator
+ "test" + File.separator + "resources" + "test" + File.separator + "resources"
+ File.separator + "chromedriver-macos");*/ + File.separator + "chromedriver-macos");*/
driver = new ChromeDriver(options); driver = new ChromeDriver();
} }
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30)); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.manage().window().maximize();
jse = (JavascriptExecutor) driver; jse = (JavascriptExecutor) driver;
} }

View File

@@ -1,6 +1,13 @@
package com.agile611.testng.webdriver; package com.agile611.testng.webdriver;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
@@ -11,7 +18,11 @@ import org.openqa.selenium.By;
import org.openqa.selenium.WebElement; import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@@ -19,46 +30,90 @@ import org.testng.annotations.Test;
public class DownloadTest extends BaseTest { public class DownloadTest extends BaseTest {
File folder; File folder;
void moureUltimFitxerDescarregat(String rutaDestiFinal) {
// 1. Ruta de la carpeta de descàrregues per defecte del Mac
String rutaDownloadsGeneral = System.getProperty("user.home") + "/Downloads";
File directori = new File(rutaDownloadsGeneral);
// 2. Esperar una mica a que el fitxer s'hagi baixat completament (pots ajustar el temps)
try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
// 3. Buscar el fitxer més recent de la carpeta
File[] fitxers = directori.listFiles();
if (fitxers != null && fitxers.length > 0) {
Arrays.sort(fitxers, Comparator.comparingLong(File::lastModified).reversed());
File ultimFitxer = fitxers[0];
// Evitem agafar fitxers temporals de descàrrega de Safari (com els .download)
if (ultimFitxer.getName().endsWith(".download")) {
System.out.println("El fitxer encara s'està descarregant...");
return;
}
// 4. Moure el fitxer a la teva ruta desitjada
try {
Path origen = ultimFitxer.toPath();
Path desti = Paths.get(rutaDestiFinal);
// Si la ruta destí és només una carpeta, hi afegim el nom del fitxer original
if (Files.isDirectory(desti)) {
desti = desti.resolve(ultimFitxer.getName());
}
Files.move(origen, desti, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Fitxer mogut correctament a: " + desti.toString());
} catch (IOException e) {
System.err.println("Error en moure el fitxer: " + e.getMessage());
}
} else {
System.err.println("No s'ha trobat cap fitxer a la carpeta de descàrregues.");
}
}
@BeforeMethod @BeforeMethod
public void setUp() { public void setUp() {
folder = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + UUID.randomUUID().toString());
folder = new File("src" + File.separator + "test"
+ File.separator + "resources"
+ File.separator + UUID.randomUUID().toString());
String downloadFilepath = folder.getAbsolutePath(); String downloadFilepath = folder.getAbsolutePath();
//Chrome if (System.getProperty("browser").equalsIgnoreCase("safari")) {
System.setProperty("webdriver.chrome.driver", "src" + File.separator + "test" + File.separator + "resources" + File.separator + "chromedriver-macos"); driver = new SafariDriver();
}
HashMap<String, Object> chromePrefs = new HashMap<String, Object>(); else if(System.getProperty("browser").equalsIgnoreCase("firefox")){
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.setAcceptInsecureCerts(true);
//options.addArguments("--headless");
driver = new ChromeDriver(options);
//Firefox //Firefox
// 1. Configurar el perfil de Firefox // 1. Configurar el perfil de Firefox
/*FirefoxProfile profile = new FirefoxProfile(); FirefoxProfile profile = new FirefoxProfile();
System.setProperty("webdriver.gecko.driver", profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;");
"src" + File.separator + "test" profile.setPreference("browser.helperApps.alwaysAsk.force", false);
+ File.separator + "resources" profile.setPreference("browser.download.manager.showWhenStarting", false);
+ File.separator + "geckodriver-macos"); profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;"); profile.setPreference("browser.download.dir", downloadFilepath);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", downloadFilepath);
// 2. Usar FirefoxOptions en lugar de DesiredCapabilities // 2. Usar FirefoxOptions en lugar de DesiredCapabilities
FirefoxOptions options = new FirefoxOptions(); FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile); options.setProfile(profile);
// Opcional: Si necesitas ejecutarlo en modo incógnito o sin interfaz gráfica (headless) // Opcional: Si necesitas ejecutarlo en modo incógnito o sin interfaz gráfica (headless)
//options.addArguments("-headless"); //options.addArguments("-headless");
// 3. Inicializar el driver // 3. Inicializar el driver
// NOTA: Ya no necesitas System.setProperty para el geckodriver. // NOTA: Ya no necesitas System.setProperty para el geckodriver.
driver = new FirefoxDriver(options);*/ driver = new FirefoxDriver(options);
} else {
//Chrome
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.setAcceptInsecureCerts(true);
//options.addArguments("--headless");
driver = new ChromeDriver(options);
}
} }
@AfterMethod @AfterMethod
@@ -76,6 +131,12 @@ public class DownloadTest extends BaseTest {
actions.dragAndDrop(link, link).build().perform(); actions.dragAndDrop(link, link).build().perform();
// Wait 2 seconds to download file // Wait 2 seconds to download file
Thread.sleep(2000); Thread.sleep(2000);
// A Safari no podem tocar les Options i hem de fer aquest "hack" per moure el fitxer descarregat a la carpeta que volem
if (System.getProperty("browser").equalsIgnoreCase("safari")) {
moureUltimFitxerDescarregat(folder.getAbsolutePath());
}
File[] listOfFiles = folder.listFiles(); File[] listOfFiles = folder.listFiles();
// Make sure the directory is not empty // Make sure the directory is not empty
assertThat(listOfFiles.length, is(not(0))); assertThat(listOfFiles.length, is(not(0)));