web-dev-qa-db-fra.com

Comment vérifier les fichiers téléchargés Selenium WebDriver?

J'ai écrit un test d'automatisation dans Selenium WebDriver à l'aide de C # et l'une des étapes nécessite le téléchargement d'un fichier XLSX à partir du serveur. Comment valider si le fichier a été téléchargé avec succès et obtenir son nom?

Cordialement

J'ai trouvé la solution avec le code source suivant:

string currentPage = Browser.Current.Url;
string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string downloadPath = Path.Combine(userPath, "Downloads");

DirectoryInfo dirInfo = new DirectoryInfo(downloadPath);

if (!dirInfo.Exists)
{
     dirInfo.Create();
}

int directoryFiles = dirInfo.EnumerateFiles().Count();

string elementXpath = "//div[@id='myDiv']/div/div/div[@class='atalhos']/a[1]";

bool isFirefox = (Browser.Current as FirefoxDriver) != null;
bool isChrome = (Browser.Current as ChromeDriver) != null;

IWebDriver browserDriver = null;

if (isChrome)
{
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.AddUserProfilePreference("download.default_directory", downloadPath);
    chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");

    browserDriver = new ChromeDriver(chromeOptions);
}
else if (isFirefox)
{               
    FirefoxProfile profile = new FirefoxProfile();                
    profile.SetPreference("browser.download.folderList", 2);                
    profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    browserDriver = new FirefoxDriver(profile);
}

browserDriver.Navigate().GoToUrl(currentPage);

WebDriverWait wait = new WebDriverWait(browserDriver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(elementXpath)));

IWebElement elemento = browserDriver.FindElement(By.XPath(elementXpath));

elemento.Click();

Thread.Sleep(7000);

dirInfo = new DirectoryInfo(downloadPath);

int currentFiles = dirInfo.EnumerateFiles().Count();

Assert.Greater(currentFiles, directoryFiles);

Dans le code ci-dessous, j'ai pris la liste des fichiers Excel dans le dossier de téléchargement. Si vous n'avez qu'un seul fichier, utilisez la propriété file.name ou, si vous avez plusieurs fichiers, essayez le code ci-dessous.

 private static string GetDownloadedFileName()
    {
          var fileName = ConfigurationManager.AppSettings["excelName"].ToString();
          string pathUser=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
          string pathDownload = Path.Combine(pathUser, "Downloads");

            DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
            FileInfo[] files = downloadDir.GetFiles("*.xls");
            var file = files.Where(x => x.Name.Replace(" ", "") == fileName + ".xls").FirstOrDefault();
            fileName = file.FullName;

            return fileName;
    }
0
Sankar G